C# 使用 ASP.NET MVC 的多参数路由

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2246481/
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-07 00:44:19  来源:igfitidea点击:

Routing with Multiple Parameters using ASP.NET MVC

c#.netasp.net-mvcrouting

提问by CodingWithoutComments

Our company is developing an API for our products and we are thinking about using ASP.NET MVC. While designing our API, we decided to use calls like the one below for the user to request information from the API in XML format:

我们公司正在为我们的产品开发 API,我们正在考虑使用 ASP.NET MVC。在设计我们的 API 时,我们决定使用如下所示的调用,让用户以 XML 格式从 API 请求信息:

http://ws.audioscrobbler.com/2.0/?method=artist.getimages&artist=cher&api_key=b25b959554ed76058ac220b7b2e0a026

http://ws.audioscrobbler.com/2.0/?method=artist.getimages&artist=cher&api_key=b25b959554ed76058ac220b7b2e0a026

As you can see, multiple parameters are passed (i.e. artistand api_key). In ASP.NET MVC, artistwould be the controller, getImagesthe action, but how would I pass multiple parameters to the action?

如您所见,传递了多个参数(即artistapi_key)。在 ASP.NET MVC 中,artist将是controller,getImages动作,但如何将多个参数传递给动作?

Is this even possible using the format above?

这甚至可以使用上面的格式吗?

采纳答案by Ryan Brunner

Parameters are directly supported in MVC by simply adding parameters onto your action methods. Given an action like the following:

通过简单地将参数添加到您的操作方法中,MVC 直接支持参数。给定如下动作:

public ActionResult GetImages(string artistName, string apiKey)

MVC will auto-populate the parameters when given a URL like:

当给定 URL 时,MVC 将自动填充参数,例如:

/Artist/GetImages/?artistName=cher&apiKey=XXX

One additional special case is parameters named "id". Any parameter named ID can be put into the path rather than the querystring, so something like:

另一种特殊情况是名为“id”的参数。任何名为 ID 的参数都可以放入路径而不是查询字符串中,例如:

public ActionResult GetImages(string id, string apiKey)

would be populated correctly with a URL like the following:

将使用如下所示的 URL 正确填充:

/Artist/GetImages/cher?apiKey=XXX

In addition, if you have more complicated scenarios, you can customize the routing rules that MVC uses to locate an action. Your global.asax file contains routing rules that can be customized. By default the rule looks like this:

另外,如果你有更复杂的场景,你可以自定义MVC用来定位动作的路由规则。您的 global.asax 文件包含可以自定义的路由规则。默认情况下,规则如下所示:

routes.MapRoute(
            "Default",                                              // Route name
            "{controller}/{action}/{id}",                           // URL with parameters
            new { controller = "Home", action = "Index", id = "" }  // Parameter defaults
        );

If you wanted to support a url like

如果你想支持一个像

/Artist/GetImages/cher/api-key

you could add a route like:

您可以添加如下路线:

routes.MapRoute(
            "ArtistImages",                                              // Route name
            "{controller}/{action}/{artistName}/{apikey}",                           // URL with parameters
            new { controller = "Home", action = "Index", artistName = "", apikey = "" }  // Parameter defaults
        );

and a method like the first example above.

和上面第一个例子一样的方法。

回答by George Stocker

You can pass arbitrary parameters through the query string, but you can also set up custom routes to handle it in a RESTful way:

您可以通过查询字符串传递任意参数,但您也可以设置自定义路由以 RESTful 方式处理它:

http://ws.audioscrobbler.com/2.0/?method=artist.getimages&artist=cher&
                                  api_key=b25b959554ed76058ac220b7b2e0a026

That could be:

那可能是:

routes.MapRoute(
    "ArtistsImages",
    "{ws}/artists/{artist}/{action}/{*apikey}",
    new { ws = "2.0", controller="artists" artist = "", action="", apikey="" }
    );

So if someone used the following route:

因此,如果有人使用以下路线:

ws.audioscrobbler.com/2.0/artists/cher/images/b25b959554ed76058ac220b7b2e0a026/

It would take them to the same place your example querystring did.

它会将它们带到您的示例查询字符串所做的相同位置。

The above is just an example, and doesn't apply the business rules and constraints you'd have to set up to make sure people didn't 'hack' the URL.

以上只是一个示例,并没有应用您必须设置的业务规则和约束,以确保人们没有“破解”URL。

回答by Bernard Vander Beken

Starting with MVC 5, you can also use Attribute Routing to move the URL parameter configuration to your controllers.

从 MVC 5 开始,您还可以使用属性路由将 URL 参数配置移动到您的控制器。

A detailed discussion is available here: http://blogs.msdn.com/b/webdev/archive/2013/10/17/attribute-routing-in-asp-net-mvc-5.aspx

详细讨论可在此处获得:http: //blogs.msdn.com/b/webdev/archive/2013/10/17/attribute-routing-in-asp-net-mvc-5.aspx

Summary:

概括:

First you enable attribute routing

首先启用属性路由

 public class RouteConfig 
 {
     public static void RegisterRoutes(RouteCollection routes)
     {
         routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

         routes.MapMvcAttributeRoutes();
     } 
 }

Then you can use attributes to define parameters and optionally data types

然后您可以使用属性来定义参数和可选的数据类型

public class BooksController : Controller
{
    // eg: /books
    // eg: /books/1430210079
    [Route("books/{isbn?}")]
    public ActionResult View(string isbn)