C# MVC 4 Web API 中的 URL 参数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9943502/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 11:18:48  来源:igfitidea点击:

URL parameters in MVC 4 Web API

c#asp.net-mvcasp.net-web-api

提问by pavel.baravik

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, 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:

导致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. Is this a bug or my misunderstanding of how MVC maps request to action?

我希望 MVC 应该没有问题地连接 URL 参数,但事实并非如此。这是错误还是我对 MVC 如何将请求映射到操作的误解?

采纳答案by Shiv Kumar

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.

所以回答你的问题......不,这不是一个错误,而是设计/预期的。

回答by Bajju

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=""}
        );