首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >MVC RegisterRoutes MapRoute

MVC RegisterRoutes MapRoute
EN

Stack Overflow用户
提问于 2017-11-29 18:50:39
回答 1查看 509关注 0票数 0
代码语言:javascript
复制
        routes.MapRoute(
            name: "Home",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        ); 

         routes.MapRoute(
             name: "Process",
             url: "Process/{action}/{id}",
             defaults: new { controller = "Process", action = "", id = UrlParameter.Optional }
        );
  1. 请你帮助我理解为什么我得到HTTP404Error当我点击http://localhost:7841/Process时,当我点击http://localhost:7841/Process/list时,我能够看到我的页面
  2. 另外,如果我硬编码控制器( url:"Home/{action}/{id}")在两个路由url中(见下文),为什么我会得到“HTTP错误403.14 -禁止的”错误。 routes.MapRoute(名称:"Home",url:"Home/{ action }/{ id }",默认值: new { controller = "Home",action= "Index",id= UrlParameter.Optional } );routes.MapRoute(名称:"Process",url:"Process/{ action }/{ id }",默认值: new { controller = "Process",action= "",id= UrlParameter.Optional } );

请帮助我了解路线。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-11-29 19:00:12

因为当您请求yourBaseUrl/Process/时,它与路由模式{controller}/{action}/{id}相匹配,这是定义的第一个路由(称为Home)的url模式。因此,它将尝试将请求发送到action方法,并且由于请求url中没有action方法段,因此它将尝试使用在该路由注册中定义的默认方法,即Index。您将获得404,因为在您的Index中没有ProcessController操作方法。如果将Index()操作方法添加到ProcessController中,它将执行该操作并返回结果。

理想情况下,您应该在通用路由定义之前定义所有特定的路由定义。如果希望/Process返回由List方法返回的响应,请将其设置为路由注册中的默认操作。

代码语言:javascript
复制
routes.MapRoute(
    name: "Process",
    url: "Process/{action}/{id}",
    defaults: new { controller = "Process", action = "List", id = UrlParameter.Optional }
);


routes.MapRoute(
     name: "Default",
     url: "{controller}/{action}/{id}",
     defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);

另一个选项是使用默认的通用路由注册,就像在RouteConfig中一样,并使用属性路由使List方法由/Process/请求处理。

代码语言:javascript
复制
public class ProcessController : Controller
{
    [System.Web.Mvc.Route("Process")]
    public ActionResult List()
    {
        return Content("process list action method :)");
    }
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/47559741

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档