Getting 404 when calling a post method on Web API - c#

I have an API controller which have standard GET,POST and Delete actions.
[Route("api/[controller]")]
[ApiController]
public class UsersController : ControllerBase
{
//Get
[HttpPost]
public async Task Post([FromBody] TestUser testUser, string tempPassword, role = "Guest")
{
}
}
Now I am adding a new action using:
[HttpPost]
[Route("api/[controller]/UpdateRole")]
public async Task Post(string email, List<string> roles)
{
}
When I am trying to call the API using postman ,
Type : POST
Endpoint : http://localhost/api/users/UpdateRole
Request body:
{
"email":"something#mail.com",
"roles":["S1","s3"]
}
But I am getting a 404 as response back. On server I can see ,
the application completed without reading the entire request body.

It seems that your overall route is /api/Users/api/Users/UpdateRoute because of how RouteAttribute works.
[Route("a")]
public class MyController
{
[Route("a/b")]
public IActionResult MyAction()
{
}
}
The above will have a route of /a/a/b because the action route is appended to the controller route in this case.
Your options are:
Change the controller route to [Route("[controller]/[action]")] and remove the action route, in which case the example above would become /MyController/MyAction
Change the action route to simply [Route("b")], in which case the full route would be a/b
Use an absolute path for the action route [Route("/a/b")], in which case the controller route would be ignored and the full route will simply be /a/b.
See here for more information about routing.
As for your issue with null values, ASP.NET Core is currently expecting email and roles as querystring parameters. Instead, you should create a model for your request body:
public class MyModel
{
public string Email { get; set; }
public List<string> Roles { get; set; }
}
And then change your action to accept it:
[HttpPost]
[Route("api/[controller]/UpdateRole")]
public async Task Post([FromBody]MyModel model)
{
}

Related

Controller route attribute only relevant for root function?

I have a question about .NET Core controller routing. Recently I discovered that the controller route attribute (which you place just above the controller) only works for the root method, or at least it seems that way.
My code:
using KrabbelMicroservice.Models;
using KrabbelMicroservice.Services.Interfaces;
using Microsoft.AspNetCore.Mvc;
namespace KrabbelMicroservice.Controllers;
[ApiController]
[Route("/profile")] // <-- This is the controller routing attribute I am talking about
public class ProfileKrabbelController : Controller
{
private readonly IProfileKrabbelService _krabbelService;
public ProfileKrabbelController(IProfileKrabbelService krabbelService)
{
_krabbelService = krabbelService;
}
[HttpGet]
public IActionResult Index()
{
// not relevant
}
[HttpGet]
[Route("/id/{krabbelId}")]
public IActionResult GetKrabbelById(long krabbelId)
{
// not relevant
}
[HttpGet]
[Route("/pid/to/{profileId}")]
public IActionResult GetKrabbelsToProfileId(long profileId)
{
// not relevant
}
[HttpGet]
[Route("/pid/from/{profileId}")]
public IActionResult GetKrabbelsFromProfileId(long profileId)
{
// not relevant
}
[HttpGet]
[Route("/pid/with/{profileId}")]
public IActionResult GetKrabbelsWithProfileId(long profileId)
{
// not relevant
}
[HttpPost]
[Route("/new")]
public IActionResult AddKrabbel(ProfileKrabbel krabbel)
{
// not relevant
}
[HttpPut]
[Route("/update")]
public IActionResult UpdateKrabbel(ProfileKrabbel krabbel)
{
// not relevant
}
[HttpDelete]
[Route("/delete")]
public IActionResult DeleteKrabbel(ProfileKrabbel krabbel)
{
// not relevant
}
}
In my swagger launch the requests look like this:
I expected that all paths would be prefixed by /profile/ but it seems like only the root function (which did not have its own route attribute) implemented the prefix.
I am not only trying to get a fix for this, but also looking for an explanation as to why my controller route attribute is ignored for the other requests. The only possibility I can think of is the specific route attributes for each endpoint overriding the controller route attribute but I would like to hear it from an expert.
Secondly I would of course also like to find a solution to this problem, preferrably not adding /profile before every seperate route but if that is the only solution so be it.
Thanks in advance!
you should be remove "/" if you have root route
ex:
[Route("test")]
[ApiController]
public class TestController3 : Controller
{
[HttpGet]
[Route("testobj")]
public TestObj Test()
{
return "test";
}
}
the even shorter in httpget
[HttpGet("testobj")]
the both output:
test/testobj

Get the full route to current action

I have a simple API with basic routing. It was setup using the default Visual Studio 2015 ASP.NET Core API template.
I have this controller and action:
[Route("api/[controller]")]
public class DocumentController : Controller
{
[HttpGet("info/{Id}")]
public async Task<Data> Get(string Id)
{
//Logic
}
}
So to reach this method, I must call GET /api/document/info/some-id-here.
Is it possible with .NET Core, inside that method, to retrieve as a string the complete route?
So I could do for example:
var myRoute = retrieveRoute();
// myRoute = "/api/document/info/some-id-here"
You can get the complete requested url using the Request option (HttpRequest) in .Net Core.
var route = Request.Path.Value;
Your final code.
[Route("api/[controller]")]
public class DocumentController : Controller
{
[HttpGet("info/{Id}")]
public async Task<Data> Get(string Id)
{
var route = Request.Path.Value;
}
}
Result route: "/api/document/info/some-id-here" //for example
You can also ask MVC to create a new route URL based on the current route values:
[Route("api/[controller]")]
public class DocumentController : Controller
{
[HttpGet("info/{Id}")]
public async Task<Data> Get(string Id)
{
//Logic
var myRoute = Url.RouteUrl(RouteData.Values);
}
}
Url.RouteUrl is a helper method that lets you build a route URL given any route values. RouteData.Values gives you the route values for the current request.
If you want the original route template on an API controller that was specified with any HttpMethod attribute then this will do it:
var routeAttribute = Url.ActionContext.ActionDescriptor.EndpointMetadata.First(d => d is HttpMethodAttribute);
var routeTemplate = ((HttpMethodAttribute)routeAttribute).Template;
If the original route attribute was: [HttpGet("Self/{id}")]
The routeTemplate value would be: "Self/{id}"
Url.ActionContext.ActionDescriptor.AttributeRouteInfo.Template
"v{version}/{cardId}/cardsTest" {$1}

Unusual [RoutePrefix] behavior in ASP.NET WebAPI

I have two Controllers as follows:
[RoutePrefix("v1/user/something")]
public class SomethingsController : ApiController
{
[Route("{id}")]
[HttpGet]
[ResponseType(typeof(SomethingsViewModel))]
public async Task<IHttpActionResult> GetAsync([FromUri]int id)
{
}
}
[RoutePrefix("v1/user")]
public class UserController : ApiController
{
[Route("{id}")]
[HttpGet]
[Authorize(Roles = "Super Admin")]
public async Task<IHttpActionResult> GetByIdAsync([FromUri]int id)
{
}
}
Now by looking at the code above, I'd think that the following two routes are being created:
v1/user/something/{id}
v1/user/{id}
But unfortunately, for some reason, that is not the case. I keep getting the following exception message when trying to access one of the above routes:
Multiple controller types were found that match the URL. This can happen if attribute routes on multiple controllers match the requested URL.
The request has found the following matching controller types: MyProject.Api.Controllers.UserController, MyProject.Api.Controllers.SomethingsController
Please help me out in figuring what I might be doing wrong or which small detail am I missing out here.
Though their route prefix are different their resolved routes match. for example v1/user/{id} will match v1/user/something/{id} where id parameter arg in the first route will take something/{id}.
Route prefix and Route attributes combine to create a full route that is added to the route table.
In a case like this you will need to use constraints in order to better differentiate the routes.
[RoutePrefix("v1/user/something")]
public class SomethingsController : ApiController {
[Route("{id:int}")]
[HttpGet]
[ResponseType(typeof(SomethingsViewModel))]
public async Task<IHttpActionResult> GetAsync([FromUri]int id) { ... }
}
[RoutePrefix("v1/user")]
public class UserController : ApiController {
[Route("{id:int}")]
[HttpGet]
[Authorize(Roles = "Super Admin")]
public async Task<IHttpActionResult> GetByIdAsync([FromUri]int id) { ... }
}
So now with the int constraint something wont be mistaken for valid parameter for the UserController.GetByIdAsync action
Reference Attribute Routing in ASP.NET Web API 2: Route Constraints
Route Constraints
Route constraints let you restrict how the parameters in the route
template are matched. The general syntax is "{parameter:constraint}".
For example:
[Route("users/{id:int}"]
public User GetUserById(int id) { ... }
[Route("users/{name}"]
public User GetUserByName(string name) { ... }
Here, the first route will only be selected if the "id" segment of the
URI is an integer. Otherwise, the second route will be chosen.

Webapi 2 Attribute Routing

I have the following routes set up in a user controller:
[EnableCors("*", "*", "*")]
[RoutePrefix("api/users")]
[Authorize]
public class UserController : ApiController
{
[Route("")]
public IHttpActionResult Get()
{
}
[HttpGet]
[Route("{id:int}")]
public IHttpActionResult Get(int id)
}
[HttpPost]
[Route("validateUser")]
public IHttpActionResult ValidateUser()
{
}
[HttpPost]
[Route("verify/{identityId}/{emailAddress}")]
public void VerifyUserEmailAddress(string identityId, string emailAddress)
{
}
}
The first three routes work just fine. But the fourth fails with a 404. I'm using fiddler to make the call:
http://localhost:39897/api/users/verify/asldkfj/jb#test.com (post is selected)
Does post require data sent in the body? Can anyone see what I'm doing wrong and why the verify route is not being found?
The .com in the email is the issue.
Sure its a valid email, but IIS treats requests with file extensions as actual file requests and tries to find it on disk. When it can't find it then you get the 404 Not Found
If you add a trailing slash / to the request it should work.
ie http://localhost:39897/api/users/verify/asldkfj/jb#test.com/

Creating a different route to a specific action

I am working on an asp.net 5 mvc api, and I am currently working on the Accounts Controller.
since I saw in many different places that there is a convention of using /api/Tokenrouting to a login in a web api. I would like to route to that specific method without the accounts prefix, I would prefer not using a different controller, and I would prefer using Attributes over routing in Startup.cs to avoid confusion in the future.
this is what I have currently
[Route("api/[controller]")]
public class AccountsController : Controller
{
[HttpPost("login")]
public async Task<JwtToken> Token([FromBody]Credentials credentials)
{
...
}
[HttpPost]
public async Task CreateUser([FromBody] userDto)
{
...
}
}
With attribute routing you can use a tilde (~) on the Action's route attribute to override the default route of the Controller if needed:
[Route("api/[controller]")]
public class AccountsController : Controller {
[HttpPost]
[Route("~/api/token")] //routes to `/api/token`
public async Task<JwtToken> Token([FromBody]Credentials credentials) {
...
}
[HttpPost]
[Route("users")] // routes to `/api/accounts/users`
public async Task CreateUser([FromBody] userDto) {
...
}
}
For ASP.NET Core it seems that the tilde ~ symbol (see accepted answer) is not needed anymore to override the controller's route prefix – instead, the following rule applies:
Route templates applied to an action that begin with a / don't get combined with route templates applied to the controller. This example matches a set of URL paths similar to the default route.
Here is an example:
[Route("foo")]
public class FooController : Controller
{
[Route("bar")] // combined with "foo" to map to route "/foo/bar"
public IActionResult Bar()
{
// ...
}
[Route("/hello/world")] // not combined; maps to route "/hello/world"
public IActionResult HelloWorld()
{
}
}
from https://learn.microsoft.com/en-us/aspnet/core/mvc/controllers/routing
[Route("[controller]/[action]")]
public class HomeController : Controller
{
[Route("~/")]
[Route("/Home")]
[Route("~/Home/Index")]
public IActionResult Index()
{
return ControllerContext.MyDisplayRouteInfo();
}
public IActionResult About()
{
return ControllerContext.MyDisplayRouteInfo();
}
}
In the preceding code, the Index method templates must prepend / or ~/ to the route templates. Route templates applied to an action that begin with / or ~/ don't get combined with route templates applied to the controller.

Categories

Resources