按查询字符串路由

时间:2012-01-08 13:43:01

标签: asp.net-mvc-3 url-routing

如果我想要一个下面的网址(我没有定义,所以我无法更改),该怎么办?

http://localhost/Something?cmd=Open&a=1&b=2

映射到MyController.Open()操作?

public class MyController : Controller
{
    public ActionResult Open(int a, int b)
    {
        //.....
    }

    public ActionResult Close(string c)
    {
        //.....
    }
}

注意:有多个可能的cmd值,每个值都映射到同一个控制器的动作。

1 个答案:

答案 0 :(得分:2)

您可以编写自定义路线:

public class MyRoute : Route
{
    public MyRoute()
        : base(
            "something",
            // TODO: replace the name of the controller with the actual
            // controller containing the Open and Close actions
            // What you have shown in your question is not an MVC controller.
            // In ASP.NET MVC controllers must derive from the Controller class
            new RouteValueDictionary(new { controller = "home" }), 
            new MvcRouteHandler()
        )
    { }

    public override RouteData GetRouteData(HttpContextBase httpContext)
    {
        var rd = base.GetRouteData(httpContext);
        if (rd == null)
        {
            return null;
        }
        var cmd = httpContext.Request.QueryString["cmd"];
        if (!string.IsNullOrEmpty(cmd))
        {
            rd.Values["action"] = cmd;
            return rd;
        }
        return null;
    }
}

然后注册此自定义路线:

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

    // register the custom route before the default route, 
    // to ensure that it handles requests to /something
    routes.Add("something", new MyRoute());

    routes.MapRoute(
        "Default",
        "{controller}/{action}/{id}",
        new { controller = "Home", action = "Index", id = UrlParameter.Optional }
    );
}
相关问题