简体   繁体   English

MVC 4 Web API中的URL参数

[英]URL parameters in MVC 4 Web API

Let say I have two methods in MVC 4 Web API controller: 假设我在MVC 4 Web API控制器中有两种方法:

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, eg: 添加一个参数,例如:

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: 导致MVC为以下请求返回404时的情况:

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. 我希望URL参数应该由MVC连接而没有问题,但事实并非如此。 Is this a bug or my misunderstanding of how MVC maps request to action? 这是一个错误还是我对MVC映射请求如何行动的误解?

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. 如果你考虑一下你正在尝试做什么以及你正在尝试的路线,你会发现你的情况下第二个参数“p”也需要被标记为可选参数。

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 完成此操作后,即URL

/controller?p=100 will map to your / controller?p = 100将映射到你的

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

method and a URL like so: 方法和URL如下:

 /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. 所以回答你的问题....不,这不是一个错误,而是设计/预期。

In the WebApiConfig add new defaults to the httproute 在WebApiConfig中,向httproute添加新的默认值

RouteParameter.Optional for the additional routes did not work for me 其他路线的RouteParameter.Optional对我不起作用

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM