Web API Advanced Options in the Middle

I have the following route mapping or WEB API

[Route("Foo/Id/{id=1}/bar")] 

I want to make Id optional as above, but on the client side, whatever I call it a route doesn't match, and I get 404 I try something like

 Foo/Id//bar 

But does not work. Is there a way to use additional parameters with web api if the parameter is not at the end?

+7
asp.net-web-api routing asp.net-web-api2
source share
4 answers

use 0 instead of an empty parameter, and when getting 0 use it as your empty one.

0
source share

refer to this article regarding route attribute

You can use it like this and provide default values.

Your attribute will look like this:

 [Route("Foo/Id/{id:int=0}/bar")] 

and then process 0 as if there was no value (as indicated above).

0
source share

I had a similar problem and my solution was to set the route attribute to nullable and pass a null argument when I would not want to provide a value. For you, it will be something like this:

 [Route("Foo/Id/{id:int?}/bar")] 

Then I processed the null condition in the controller action logic. I think you could set the default value in the controller action like this: (C #):

 ///<summary> /// Get my foo bars ///</summary> [Route("Foo/Id/{id:int?}/bar")] public HttpResponseMessage Get(int? id) { var fooId = id ?? 1; // fooId will be of type System.Int32. ... 

So, you could name any of them:

 ~/Foo/Id/null/bar ~/Foo/Id/5/bar 

This solution works for me.

0
source share

You cannot use // in the url. The only way to do what you need is to display 2 routes for one endpoint. For reference

 config.Routes.MapHttpRoute( name: "BarRoute", routeTemplate: "Foo/Id/{id}/bar", defaults: new { controller = "Foo" }); config.Routes.MapHttpRoute( name: "BarDefaultRoute", routeTemplate: "Foo/Id/bar", defaults: new { controller = "Foo" }); 
0
source share

All Articles