pavel.baravik
pavel.baravik

Reputation: 709

URL parameters in MVC 4 Web API

Let say I have two methods in MVC 4 Web API controller:

public IQueryable<A> Get() {}

And

public A Get(int id) {}

And the following route:

routes.MapHttpRoute(
    name: "Default", 
    routeTemplate: "{controller}/{id}",
    defaults: new { id = RouteParameter.Optional }
);

This works as expected. Adding a one more parameter, e.g.:

public IQueryable<A> Get(int p) {}

public A Get(int id, int p) {}

leads to the situation when MVC returns 404 for the following request:

GET /controller?p=100

Or

GET /controller/1?p=100

with message "No action was found on the controller 'controller' that matches the request"

I expect that URL parameters should be wired by MVC without issues, but it is not true. Is this a bug or my misunderstanding of how MVC maps request to action?

Upvotes: 7

Views: 30685

Answers (2)

Bajju
Bajju

Reputation: 935

In the WebApiConfig add new defaults to the httproute

RouteParameter.Optional for the additional routes did not work for me

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

Upvotes: 0

Shiv Kumar
Shiv Kumar

Reputation: 9799

If you think about what you're attempting to do and the routes you're trying, you'll realize that the second parameter "p" in your case, needs to be marked as an optional parameter as well.

that is your route should be defined like so:

routes.MapHttpRoute(
name: "Default", 
routeTemplate: "{controller}/{id}/{p}",
defaults: new { id = RouteParameter.Optional, p = RouteParameter.Optional });

Once you do this, the URL

/controller?p=100 will map to your

public IQueryable<A> Get(int p) {}

method and a URL like so:

 /controller/1?p=100

will map to your

public A Get(int id, int p) {}

method, as you expect.

So to answer your questions....no this is not a bug but as designed/expected.

Upvotes: 8

Related Questions