WebAPI: Why do these methods match the routing template? - c#

I just re-read the Routing in ASP.NET WebAPI document, and unless I'm missing something, by default WebAPI should only match methods that start with the HTTP verb. So why do I get this error when doing a POST against /api/mymodels:
ExceptionMessage, Multiple actions were found that match the request:
Post on type MyApp.Controllers.MyModelController
MaterializerFactory on type Pyro.Controllers.MyModelsController
MaterializerFactory on type Pyro.Controllers.MyModelsController
QueryableFactory on type Pyro.Controllers.MyModelsController
Only the first one should match. Here are the routes from my WebApiConfig.cs:
config.Routes.MapHttpRoute(
name: "Children",
routeTemplate: "api/{controller}/{id}/{childroute}/{childid}",
defaults: new { childid = RouteParameter.Optional }
);
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
Here are the signatures for the erroneously matching methods:
public override JSONAPI.Core.IMaterializer MaterializerFactory() {}
public override TM MaterializerFactory<TM>() {}
public override IQueryable<T> QueryableFactory(Core.IMaterializer materializer = null) {}
The only possibly unusual thing about those is that they are inherited from an intermediate subclass of ApiController that I created…though I can't see how that would matter.
None of my methods are decorated with any WebAPI attributes (e.g. AcceptVerbs, HttpPost, etc.). If I decorate one of the above with [NonAction] it disappears from the list…but I don't know why it's even trying to match methods with those names?

Grrrr…okay, then I re-read the Routing and Action Selection in ASP.NET Web API, and buried in there is this gem:
HTTP Methods. The framework only chooses actions that match the HTTP method of the request, determined as follows:
You can specify the HTTP method with an attribute: AcceptVerbs, HttpDelete, HttpGet, HttpHead, HttpOptions, HttpPatch, HttpPost, or HttpPut.
Otherwise, if the name of the controller method starts with "Get", "Post", "Put", "Delete", "Head", "Options", or "Patch", then by convention the action supports that HTTP method.
If none of the above, the method supports POST.
Okay, so this doesn't really stop you from decomposing your code into methods, you just can't make any of them public, or you have to put [NonAction] on them. Still, I wish that was far more obvious than a bullet buried in the "advanced topics" document.

Related

Web API methods never get routed to

I've played with web api a bit before, and I always seem to run into the same problem where my methods do not get routed to.
My application has that application insights package and so I can see that it captures the requests I make - by looking at the requests line above my method signature, but they never actually execute and App Insights reports a failed request.
Here is my WebApiConfig
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
;
Here is my simple controller and method
public class ExampleController : ApiController
{
[HttpGet]
[ActionName("Test")]
public IHttpActionResult Test()
{
return Ok();
}
}
This is part of an MVC application, so when I launch the project, the Home/Index view is displayed in my browser. I then go to postman and create a new Get request pointing at
http://localhost:port/api/Example/Test
But this results in a 404.
I must be doing something wrong as I always run into this
The default mapping for WebAPI does not include the action as part of the route, as it, by default, expects the controller to be the main identifier for a resource and the GET/POST/PUT/DELETE verb to define which operation is run.
So, even though you are manually specifying the ActionName of "Test", there's nothing in the default handler to pattern match against it.
You could adjust your default mapping to include actions, like so:
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
;
However, you might find you prefer attribute routing (I know I do), which you could apply to your controller like this:
[RoutePrefix("api/Example")]
public class ExampleController : ApiController
{
[HttpGet]
[Route("Test")]
public IHttpActionResult Test()
{
return Ok();
}
}
To enable attribute routing, you will need to add the following to your startup configuration:
config.MapHttpAttributeRoutes();

Get Request and APIs with/without parameter

I have two APIs,
[HttpGet]
public bool WithoutParamBooleanResponse()
and
[HttpGet]
public string ComplexReferenceTypeParamStringResponse([FromUri]ComplexRefType VariableComplexRef)
However, this leads to having error
multiple actions were found that match the request web api get.
If I were to add another dummy parameter for the second method, the whole thing works. Could someone explain why a parameterless method and a method with a complex parameter are seen similar by the API ?
why a parameterless method and a method with a complex parameter are
seen similar by the API ?
When a parameter is annotated with FromUri attribute and is a complex type, the value is constructed from the query params, therefore the route for both methods would be the same (since the query params are not taken into account).
Try to create a new route like:
config.Routes.MapHttpRoute(
name: "ComplexRefType",
routeTemplate: "api/{controller}/{action}/{VariableComplexRef}",
defaults: new { VariableComplexRef = RouteParameter.Optional }
);
and try to add attribute on your action
[Route("ComplexReferenceTypeParamStringResponse/{VariableComplexRef?}"]
You need to add an action to your routing url.
config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{action}/{id}", defaults: new { id = RouteParameter.Optional }
When calling a route and only passing in a controller, the routing assumes there is only one action for each method(GET,POST..) and looks for it. This is why you are having an error with more than one GET.
When you also pass an action, it is more specific to look for the correct action with this method

ASP.NET Web API Error: No HTTP resource was found that matches the request URL

I checked other sulotion sugessions that asked and answered here, but still couldn't find what's wrong with my own code.
I have a 'members' and 'fals' (means something like blogpost) controllers. every member has its own multiple 'fals' records, so I wanted to list 'fals' belongs to spesific member.
I wanted to add a custom action to my Web API to do this job, here is it:
[HttpGet, ActionName("fals"), Route("members/{id}/fals")]
public IQueryable<Fal> fals(int id)
{
Member member = db.Members.Find(id);
return member.Fals();
}
So, here is WebApiConfig customization:
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}/{action}",
defaults: new { id = RouteParameter.Optional, action = RouteParameter.Optional }
);
config.Routes.MapHttpRoute(
name: "DefaultApiWithAction",
routeTemplate: "api/{controller}/{id}/{action}"
);
I know there are two Route, even if I comment or uncomment the second Route it changes nothing.
When I try to call http://localhost:51601/api/members/1/fals URL it says:
{
"Message": "No HTTP resource was found that matches the request URI 'http://localhost:51601/api/members/1/fals'.",
"MessageDetail": "No action was found on the controller 'Members' that matches the name 'fals'."}
ID 1 existed, as I pasted the code fals existed, but couldn't figured it out.
Thanks!
I'm not sure if you are using attribute routing or not, but try removing the Route attribute from the controller action.
[HttpGet, ActionName("fals")]
If the route is "interfering" with the conventional routing I expect this would work, or you could also try calling the URL without the /api/ part because that it missing from the Route you have specified in the attribute.

Asp.NET Web API throwing 404 instead of 400

I have built a service in .NET 4.5 and Entity Framework 6, using the ASP.NET Web API template. When I make a GET request to the service and omit a required parameter, it is returning a 404 - Not Found, instead of a 400 - Bad Request. I tried checking to see if the required parameters are null, but it's not even reaching the code inside the method (see code below). My question is how do I change the default response or make it return 400 for missing required parameters.
[Route("item")]
[HttpGet]
public IHttpActionResult GetItem(string reqParam1, string reqParam2)
{
if (reqParam1 == null || reqParam2 == null)
throw new HttpResponseException(HttpStatusCode.BadRequest);
//remainder of code here
}
Here is the webAPI.config file. I don't think that I have modified it from the default.
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
Just a note: the API isn't accessing information such as item/electronics/tvs but more like items where item is green and is square, where those descriptions are mandatory to pass in - so the query is like /item?color=green&shape=square.
The server returns a 404 because it cannot find the route you are trying to access. Actually the arguments should be a part of your route, as optionals or not: Route("items/{reqParam1}/{reqParam2}")
If you defined them as optionals the route should still be called if you use just items and you can throw the BadRequest. If not optionals then probably the NotFound will still be thrown.
You should also post the webApi config, so that we can see the base route mapping.
EDIT
take the following route example:
config.Routes.MapHttpRoute(
name: "RunsWithParams",
routeTemplate: "api/{controller}/{project}/{skip}/{take}",
defaults: new { take = RouteParameter.Optional, skip = RouteParameter.Optional }
);
the project param is mandatory, the remaining are optional. you can call with just the project, or the remaining, and if you use just one of the Optionals then 404 is thrown, because the route is not defined.
This is the same as using the decorators, so it does not exactly solve your issue, but explains a bit better the routing. Still, I don't see why you need a BadRequest in particular.
Yet another edit:
To use the request url parameters as you mention at the end of the post, you just need to use the [FromUri] decorator, see this page for more details, and a breef example follows:
// POST api/files/{project}?target={target}
public HttpResponseMessage Post(string project, string target, [FromUri]string fname){...}

Using attribute routing and a global route for the same controller action

So, we're developing a webapi-heavy application that serves multiple types of clients (including a website that's a JavaScript client and multiple C# clients), and we'd like to use attribute routing to make friendlier urls. Something like this:
[RoutePrefix(Constants.RoutePrefixes.Api + "foo")]
[HttpPut]
FooController : ApiController
{
[Route("{fooId}/sub/{subFooId}")]
[HttpPut]
public HttpResponseMessage UpdateAFoo(int fooId, int subFooId)
{
return Request.CreateResponse(HttpStatusCode.OK);
}
}
And a request to /api/foo/1/sub/2 would hit this controller, as expected.
However, we have a message handler built into one of our default routes for processing identity tokens, and requests coming from clients that require that special behavior still have to use that route, or at least something that runs the appropriate message handler, and the following request (which uses that other route):
/integration/foo?fooId=1&subFooId=2
..gives me an error that no suitable controller could be found to handle the request. If I remove the route attribute, this second request hits my action method as expected.
I've read in several places that you can use both default and attribute routes, and I have both working in the application, but I haven't been able to use both for a specific action.
My route config looks like this:
public static void RegisterHttpRoutes(HttpConfiguration configuration)
{
var routes = configuration.Routes;
configuration.MapHttpAttributeRoutes();
routes.MapHttpRoute(
name: Constants.RouteNames.Api,
routeTemplate: Constants.RoutePrefixes.Api + "{controller}/{id}/{p}",
defaults: new { id = RouteParameter.Optional, p = RouteParameter.Optional }
);
routes.MapHttpRoute(
name: Constants.RouteNames.IntegrationApi,
routeTemplate: Constants.RoutePrefixes.IntegrationApi + "{controller}/{id}/{p}",
defaults: new { id = RouteParameter.Optional, p = RouteParameter.Optional },
constraints: null,
handler: new SuperDuperAuthenticationHandler())
);
}
Is that just how it works? Do I need a separate action without the route attribute? Is there a way to specify message handlers for attribute routes? Can I have both attribute and convention routing apply to the same action method? I'm not really clear on what my options are.
Controllers/Actions which are decorated with attribute routes cannot be reached via routes matched by conventional routing...so the behavior that you are seeing is expected...
Per-route message handlers are not supported for attribute routes.
Can you use AuthenticationFilterAttribute for your scenario?...if you need this filter for a set of controllers, then you could probably create a base controller decorated with this filter and let all these set of controller derive from it...

Categories

Resources