Wildcard in the WebAPI Route Pattern

I set the route pattern:

config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}/{*wildcard}", defaults: new { id = RouteParameter.Optional } ); 

controller action signature:

 public IEnumerable<object> Get(Int64 id,string abc) 

I tried matching it with the URL http://mymachine.com/api/Individuals/1?abc=4 , but that gives me an exception

{"$ id": "1", "Message": "An error has occurred.", "ExceptionMessage": "The reference to the object is not set to the instance from the object" "ExceptionType.": "System.NullReferenceException" "StackTrace ":" in System.Web.Http.ValueProviders.Providers.RouteDataValueProvider.d__4.MoveNext () \ r \ n

Strange, http://mymachine.com/api/Individuals?id=1&abc=4 corresponds to the controller, action and parameters.

I thought: " {id} " from "api / {controller} / {id} / {* wildcard}" will work.

Why?

+6
source share
2 answers

The wildcard will indicate to the routing engine that the rest of the URI matches the route parameter (for example, see the section "Get books by publication date" in this article ).

This does not mean that any arbitrary named variable matches any parameter - it is that by default WebApi uses elements in a querystring regardless of the configuration of your route (therefore, why you used the second URI - it did not match any route).

It does not match {id} in your route because it was expecting a parameter named {wildcard} that was not marked as optional.

To illustrate, if you just changed the "wildcard" to "abc":

 config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}/{*abc}", defaults: new {id = RouteParameter.Optional}); 

Then it will successfully match the following URI:

http://mymachine.com/api/Individual/1/a/b/c

With id=1, abc=a/b/c

To fix, just remove the template from your route so that it looks like this:

 config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new {id = RouteParameter.Optional}); 
+7
source

The answer from gooid is correct. I just want to answer the second part of the question:

Strange, http://mymachine.com/api/Individuals?id=1&abc=4 corresponds to the controller, action and parameters.

Since you have id = RouteParameter.Optional, if the route does not contain an identifier, it still matches the route pattern. The placeholder {* wildcard} searches for the rest of the route and places it in the route dictionary under the wildcard key. In this case, it is an empty string (or null).

Remember that query parameters are also included in the route dictionary. Therefore, your route dictionary will be: {"id": "1", "abc": "4", "wildcard": ""}

For more information you can see http://www.asp.net/web-api/overview/web-api-routing-and-actions/routing-in-aspnet-web-api

+4
source

Source: https://habr.com/ru/post/957182/


All Articles