如何在 ASP.NET MVC 中使用查询字符串路由 URL? [英] How do I route a URL with a querystring in ASP.NET MVC?

查看:25
本文介绍了如何在 ASP.NET MVC 中使用查询字符串路由 URL?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

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:

代码:

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

异常:

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

推荐答案

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

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 会自动将查询字符串参数映射到控制器中方法中的参数.

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

这篇关于如何在 ASP.NET MVC 中使用查询字符串路由 URL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆