asp.net-mvc 如何在 ASP.NET MVC 中使用查询字符串路由 URL?

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

How do I route a URL with a querystring in ASP.NET MVC?

asp.net-mvcroutingasp.net-mvc-routing

提问by Jason Underhill

I'm trying to setup a custom route in MVC to take a URL from another system in the following format:

我正在尝试在 MVC 中设置自定义路由,以采用以下格式从另一个系统获取 URL:

../ABC/ABC01?Key=123&Group=456

../ABC/ABC01?Key=123&Group=456

The 01 after the second ABC is a step number this will change and the Key and Group parameters will change. I need to route this to one action in a controller with the step number key and group as paramters. I've attempted the following code however it throws an exception:

第二个 ABC 之后的 01 是一个步骤编号,这将更改,并且键和组参数将更改。我需要将其路由到控制器中的一个动作,并使用步骤编号键和组作为参数。我尝试了以下代码,但它引发了异常:

Code:

代码:

routes.MapRoute(
    "OpenCase", 
    "ABC/ABC{stepNo}?Key={key}&Group={group}",
    new {controller = "ABC1", action = "OpenCase"}
);

Exception:

例外:

`The route URL cannot start with a '/' or '~' character and it cannot contain a '?' character.`

回答by Hector Correa

You cannot include the query string in the route. Try with a route like this:

您不能在路由中包含查询字符串。尝试这样的路线:

routes.MapRoute("OpenCase", "ABC/ABC{stepNo}",
   new { controller = "ABC1", action = "OpenCase" });

Then, on your controller add a method like this:

然后,在您的控制器上添加一个这样的方法:

public class ABC1 : Controller
{
    public ActionResult OpenCase(string stepno, string key, string group)
    {
        // do stuff here
        return View();
    }        
}

ASP.NET MVC will automatically map the query string parameters to the parameters in the method in the controller.

ASP.NET MVC 会自动将查询字符串参数映射到控制器中方法中的参数。

回答by George Stocker

When defining routes, you cannot use a /at the beginning of the route:

定义路由时,不能/在路由的开头使用 a :

routes.MapRoute("OpenCase",
    "/ABC/{controller}/{key}/{group}", // Bad. Uses a / at the beginning
    new { controller = "", action = "OpenCase" },
    new { key = @"\d+", group = @"\d+" }
    );

routes.MapRoute("OpenCase",
    "ABC/{controller}/{key}/{group}",  // Good. No / at the beginning
    new { controller = "", action = "OpenCase" },
    new { key = @"\d+", group = @"\d+" }
    );

Try this:

尝试这个:

routes.MapRoute("OpenCase",
    "ABC/{controller}/{key}/{group}",
    new { controller = "", action = "OpenCase" },
    new { key = @"\d+", group = @"\d+" }
    );

Then your action should look as follows:

那么您的操作应如下所示:

public ActionResult OpenCase(int key, int group)
{
    //do stuff here
}

It looks like you're putting together the stepNoand the "ABC" to get a controller that is ABC1. That's why I replaced that section of the URL with {controller}.

看起来您正在将stepNo和“ABC”放在一起以获得一个控制器ABC1。这就是为什么我用{controller}.

Since you also have a route that defines the 'key', and 'group', the above route will also catch your initial URL and send it to the action.

由于您还有一个定义“键”和“组”的路由,因此上述路由还将捕获您的初始 URL 并将其发送到操作。

回答by Tomas Kubes

There is no reason to use routing based in querystring in new ASP.NET MVC project. It can be useful for old project that has been converted from classic ASP.NET project and you want to preserve URLs.

没有理由在新的 ASP.NET MVC 项目中使用基于查询字符串的路由。它对于从经典 ASP.NET 项目转换而来的旧项目很有用,并且您希望保留 URL。

One solution can be attribute routing.

一种解决方案可以是属性路由。

Another solution can be in writting custom routing by deriving from RouteBase:

另一种解决方案是通过从 RouteBase 派生来编写自定义路由:

public class MyOldClassicAspRouting : RouteBase
{

  public override RouteData GetRouteData(HttpContextBase httpContext)
  {
    if (httpContext.Request.Headers == null) //for unittest
      return null;

    var queryString = httpContext.Request.QueryString;

    //add your logic here based on querystring
    RouteData routeData = new RouteData(this, new MvcRouteHandler());
    routeData.Values.Add("controller", "...");
    routeData.Values.Add("action", "...");
  }

  public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values)
  {
     //Implement your formating Url formating here
     return null;
  }
}

And register your custom routing class

并注册您的自定义路由类

public static void RegisterRoutes(RouteCollection routes)
{
  ...

  routes.Add(new MyOldClassicAspRouting ());
}

回答by RFex

The query string arguments generally are specific of that controller and of that specific application logic.

查询字符串参数通常特定于该控制器和特定应用程序逻辑。

So it will better if this isn't written in route rules, that are general.

所以如果这不是写在路由规则中会更好,这是通用的。

You can embed detection of query string on action argument in the following way.

您可以通过以下方式将查询字符串的检测嵌入到 action 参数中。

I think that is better to have one Controller for handling StepNo.

我认为最好有一个控制器来处理 StepNo。

public class ABC : Controller
{
    public ActionResult OpenCase(OpenCaseArguments arg)
    {
        // do stuff here
        // use arg.StepNo, arg.Key and arg.Group as You need
        return View();
    }        
}

public class OpenCaseArguments
{
    private string _id;
    public string id
    {
        get
        {
            return _id;
        }

        set
        {
            _id = value; // keep original value;
            ParseQueryString(value);
        }
    }

    public string  StepNo { get; set; }
    public string Key { get; set; }
    public string Group { get; set; }

    private void ParseQueryString(string qs)
    {
        var n = qs.IndexOf('?');
        if (n < 0) return;
        StepNo = qs.Substring(0, n); // extract the first part eg. {stepNo}
        NameValueCollection parms = HttpUtility.ParseQueryString(qs.Substring(n + 1));
        if (parms.Get("Key") != null) Key = parms.Get("Key");
        if (parms.Get("Group") != null) Group = parms.Get("Group");
    }

}

ModelBinder assign {id} value to the id field of OpenCaseArguments. The set method handle querystring split logic.

ModelBinder 将 {id} 值分配给 OpenCaseArguments 的 id 字段。set 方法处理查询字符串拆分逻辑。

And keep routing this way. Note routing get your querystring in id argument.

并继续以这种方式路由。注意路由在 id 参数中获取您的查询字符串。

routes.MapRoute(
    "OpenCase", 
    "ABC/OpenCase/{id}",
    new {controller = "ABC", action = "OpenCase"}
);

I have used this method for getting multiple fields key value on controller action.

我已使用此方法获取控制器操作上的多个字段键值。