首页 文章

使用基于ASP.NET MVC属性的路由映射器

提问于
浏览
2

在我的ASP.NET MVC应用程序中,我想使用this ASP.NET MVC Attribute Based Route Mapper,首先宣布here .

到目前为止,我理解如何实现使用它的代码,但我遇到了一些问题,我认为过去使用过这种基于属性的路由映射器的人将能够回答这些问题 .

  • How do I use it with ActionResults that are for HTTP POSTs? 换句话说,它如何与表单提交等一起使用?我应该只放入 GET 方法的URL,还是应该使用没有任何参数的 GET 方法URL(如 HTTP POST 中它们不通过URL传入)?

  • How do I use it with "URL querystring parameters"? 属性是否可以配置为映射到 /controller/action?id=value 而不是 /controller/action/{id} 的路由?

提前致谢 .

1 回答

  • 1

    如何将其与针对HTTP POST的ActionResults一起使用?

    您使用 [HttpPost] 属性装饰要发布到的操作:

    [Url("")]
    public ActionResult Index() { return View(); }
    
    [Url("")]
    [HttpPost]
    public ActionResult Index(string id) { return View(); }
    

    如果您决定为POST操作指定其他名称:

    [Url("")]
    public ActionResult Index() { return View(); }
    
    [Url("foo")]
    [HttpPost]
    public ActionResult Index(string id) { return View(); }
    

    您需要在辅助方法中提供此名称:

    <% using (Html.BeginForm("foo", "home", new { id = "123" })) { %>
    

    如何将其与“URL查询字符串参数”一起使用?

    查询字符串参数不是路由定义的一部分 . 您始终可以在控制器操作中将其作为操作参数或从 Request.Params 获取 .

    id 参数而言,它是在 Application_Start 中配置的,因此如果您希望它出现在查询字符串中而不是路由的一部分,只需将其从此路由定义中删除:

    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
        routes.MapRoutes();
        routes.MapRoute(
            "Default",
            "{controller}/{action}",
            new { controller = "Home", action = "Index" }
        );
    }
    

相关问题