I just started using ASP.NET Web API 2.1 and have encountered a limitation. Using Attribute Routing, I can do the following:
[Route("item/{id:int}")]
public IHttpActionResult GetItem(int id)
{
...
}
The URL /item/5 will be routed to this action, but the URL /item/abc will not, because of the int constraint in {id:int}.
I tried changing my URL so that the id parameter was in the query string along with its constraint, despite the use of route constraints on query parameters never being mentioned or demonstrated in the documentation.
[Route("item?{id:int}")]
public IHttpActionResult GetItem(int id)
{
...
}
If I try to run now, I get an error on the Configure method call in Application_Start.
protected void Application_Start()
{
GlobalConfiguration.Configure(WebApiConfig.Register);
}
The message is as follows.
ArgumentException was unhandled by user code
The route template cannot start with a '/' or '~' character and it cannot contain a '?' character.
Two things bother me about this.
First, the section documenting Route Prefixes on MSDN makes clear that placing a ~ character at the start of the route template is completely acceptable. I tried it, and it works as documented.
Second, if not like this, how can I place a route constraint on a query parameter? Consider the following, with the route constraint removed.
[Route("item")]
public IHttpActionResult GetItem(int id)
{
...
}
The URL /item/5 will be routed to this action, with id set to 5 - but so will the URL /item/abc, with id set to 0.
Is there no way to place a route constraint on a query parameter?
According to http://attributerouting.net/#asp-net-web-api (†), this is not possible:
"Beware! Due to integration issues with the Web API WebHost framework, the following features will not work: …
querystring parameter constraints, …"
†) Note that this answer was written for a previous version of Web API where attribute routing was done using a separate AttributeRouting.WebApi NuGet package. Attribute routing has since been incorporated into the Web API core. Nevertheless, it appears that constraints on query string parameters are still not supported out of the box.
Related
I have an ASP.Net Core WebAPI, I got below requirement as
I have 2 methods to handle HTTP GET requests, the first one for GetCustomer by id(string) and the other one to GetCustomer by email(string).
//GET : api/customers/2913a1ad-d990-412a-8e30-dbe464c2a85e
[HttpGet("{id}")]
public async Task<ActionResult<Customer>> GetCustomer([FromRoute]string id)
{
}
// GET: api/customers/myemail#gmail.com
[HttpGet("{name}")]
public async Task<ActionResult<Customer>> GetCustomerByEmail([FromRoute]string email)
{
}
when I try to this Endpoint, I get exception as:
Microsoft.AspNetCore.Routing.Matching.AmbiguousMatchException: The request matched multiple endpoints.
Which is quite Obivious & understood.
It could be easily addressed by appending/prepending some string in the route like
/api/customer/{id}
/api/customer/emai/{id}
However not so convinced with this apporach however on googling I get the below SO link
How to handle multiple endpoints in ASP.Net Core 3 Web API properly
But this guy has one parameter as int while the other as string so route constraint rescued.
however, I see some people posting/suggesting on the same post to add [Route("")] but I didn't get how this attribute is useful ?
afaik, Route("") and HTTPGet("") //any HttpVerb serves the same purpose?
Anyways how could I handle my requirement elegantly?
You can add route constraints to disambiguate between the two routes:
[HttpGet("{id:guid}")]
[HttpGet("{name}")]
You could also create your own email constraint or use regex(.) constraint for the email parameter.
I'm using dot.net WebApi2 and I'm getting Veracode Flaw from code scan:
'The Controller's Action is missing a Route Attribute that will perform input validation on Action parameters using a Route Constraint....
Remediation: Make sure to use RouteAttribute objects with a Route Constraint on each Action'
The action referred to is:
[Route]
[HttpGet]
public IHttpActionResult Get(int? offset = null, int? rows = null)
{
...
}
Since I only have optional parameters, they are not specified in the Route attribute. If I do by changing thr route annotation to:
[Route("{offset:int?}/{rows:int?}"]
the route would show in the swagger api help page like this:
GET /api/v1/foo/{offset}/{rows}
instead of (what we want to show):
GET /api/v1/foo
the help page would also have those parameters marked as required, even though they should not be.
Is there a way I can please Veracode and not spoil my swagger doc's?
My application is an ASP.NET Core 1.0 Web API.
[HttpGet("{someData:MinLength(5):MaxLength(5)}")]
[Produces("application/json")]
public async Task<IActionResult> GetSomeData(string someData)
{
return this.Ok(JsonConvert.SerializeObject("Data is: " + someData));
}
So when i pass a parameter with the length 6, the controller returns the Response Code 404 and the Response body no content because the parameter doesnt have the length 5.
This information is pretty useless for me, is there a way to return a more usefull error message?
I know i could just hardcode the error message in every controller like that:
[HttpGet("{someData}")]
[Produces("application/json")]
public async Task<IActionResult> GetSomeData(string someData)
{
if (someData.Length != 5)
{
return this.StatusCode(404, JsonConvert.SerializeObject("The data has to be 5 digits long."));
}
return this.Ok(JsonConvert.SerializeObject("Data is: " + someData));
}
The problem about this is, I have many controllers in my application and I dont want to validate the parameters everytime.
Is there a way the controller returns a more usefull Responsebody by itself? Or do I really have to add a validation method in each controller and forget about the [HttpGet] parameters and its error return?
Thank you very much
Route constraints are used to restrict which requested paths make it to a given action / route destination. They're not meant to perform model validation - that's done later and through a separate mechanism. If the request doesn't conform to your route constraints, it simply won't match that route. If it doesn't match any route, you'll get a 404.
As you noted in your own answer, this is covered in the routing docs: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/routing#route-template-reference
Alright I found an answer:
It's not possible to get better error messages.
Warning
Avoid using constraints for input validation, because doing so means
that invalid input will result in a 404 (Not Found) instead of a 400
with an appropriate error message. Route constraints should be used to
disambiguate between similar routes, not to validate the inputs for a
particular route.
found here
I am using WebAPI 2 with EF and scaffolding webapi controllers from visual studio.
Each controller is created with 4 default verbs (GET,PUT,DELETE,POST) and 5 actions. while there are two versions of GET action.
IQueryable<entity> GetEntities ()
Task<IHttpActionResult> GetEntity(GUID key) // default is int id but I changed to guid.
I am using attribute routing and route prefix for the controller. just some fancy keywords for better management of url. [RoutePrefix("api/v3/Company")]
Problem :
Ideally when a wrong parameter is sent in url, it should return error, but it is not raising error, instead it fall back to the action without parameter.while if I send a wrong GUID, it shows error.
Like if I call :
http://localhost:8080/api/v3/Company/1f7dc74f-af14-428d-aa31-147628e965b2
it shows the right result.
when I call :
http://localhost:8080/api/v3/Company/1f7dc74f-af14-428d-aa31-147628e96500 (wrong key)
it set back to GetEntity() function and shows all records
when I call:
http://localhost:8080/api/v3/Company/1 (not a GUID length parameter)
it do the same and shows all records.
I am using attribute [Route("{id:guid}")]
Really appreciate if I can get some guidance on this!
It is most likely that the route is defaulting back to the convention-based mapping.
You need to explicitly make apply the route attribute on actions to let the routing know that it is the default route got GET
[RoutePrefix("api/v3/Company")]
public class CompanyController : ApiController {
//GET api/v3/Company
[HttpGet]
[Route("")] //Default Get
public IQueryable GetEntities() { ... }
//GET api/v3/Company/1f7dc74f-af14-428d-aa31-147628e965b2
[HttpGet]
[Route("{id:guid}")] // ALSO NOTE THAT THE PARAMETER NAMES HAVE TO MATCH
public Task<IHttpActionResult> GetEntity(Guid id) { ... }
//...other code removed for brevity
}
Make sure that attribute routing is enabled in the web api config
config.MapHttpAttributeRoutes();
I'm presently working on a project that has been upgraded to Webapi2 from Webapi. Part of the conversion includes the switch to using attribute based routing.
I've appropriately setup my routes in the Global.asax (as follows)
GlobalConfiguration.Configure(config => config.MapHttpAttributeRoutes());
and removed the previous routing configuration.
I have decorated all of my API controllers with the appropriate System.Web.Http.RouteAttribute and System.Web.Http.RoutePrefixAttribute attributes.
If I inspect System.Web.Http.GlobalConfiguration.Configuration.Routes with the debugger I can see that all my expected routes are registered in the collection. Likewise the appropriate routes are available within the included generated Webapi Help Page documentation as expected.
Even though all appears to be setup properly a good number of my REST calls result in a 404 not found response from the server.
I've found some notable similarities specific to GET methods (this is all I've tested so far)
If a method accepts 0 parameters it will fail
If a route overrides the prefix it will fail
If a method takes a string parameter it is likely to succeed
return type seems to have no affect
Naming a route seems to have no affect
Ordering a route seems to have no affect
Renaming the underlying method seems to have no affect
Worth noting is that my API controllers appear in a separate area, but given that some routes do work I don't expect this to be the issue at hand.
Example of non-functional method call
[RoutePrefix("api/postman")]
public class PostmanApiController : ApiController
{
...
[HttpGet]
[Route("all", Name = "GetPostmanCollection")]
[ResponseType(typeof (PostmanCollectionGet))]
public IHttpActionResult GetPostmanCollection()
{
return Ok(...);
}
...
}
I expect this to be available via http://[application-root]/api/postman/all
Interestingly enough a call to
Url.Link("GetPostmanCollection", null)
will return the above expected url
A very similar example of method calls within the same controller where some work and some do not.
[RoutePrefix("api/machine")]
public class MachineApiController : ApiController
{
...
[HttpGet]
[Route("byowner/{owner}", Name = "GetPostmanCollection")]
public IEnumerable<string> GetByOwner([FromUri] string owner)
{
...
}
...
[HttpGet]
[Route("~/api/oses/{osType}")]
public IEnumerable<OsAndVersionGet> GetOSes([FromUri] string osType)
{
...
}
...
}
Where a call to http://[application-root]/api/machineby/ownername succeeds and http://[application-root]/api/oses/osType does not.
I've been poking at this far too long, any idea as to what the issue may be?
Check that you configure your HttpConfiguration via the MapHttpAttributeRoutes method before any ASP.NET MVC routing registration.
In accordance to Microsoft's CodePlex entry on Attribute Routing in MVC and Web API the Design section states:
In most cases, MapHttpAttributeRoutes or MapMvcAttributeRoutes will be
called first so that attribute routes are registered before the global
routes (and therefore get a chance to supersede global routes).
Requests to attribute routed controllers would also be filtered to
only those that originated from an attribute route.
Therefore, within the Global.asax (or where registering routes) it is appropriate to call:
GlobalConfiguration.Configure(c => c.MapHttpAttributeRoutes()); // http routes
RouteTable.Routes.MapRoute(...); // mvc routes
In my case it was a stupid mistake, I am posting this so people behind me making the same mistake may read this before they check everything else at quantum level.
My mistake was, my controller's name did not end with the word Controller.
Happy new year