Attribute Routing not working in areas

前端 未结 2 1102
栀梦
栀梦 2020-12-02 12:57

Scenario: I have a Forms area in my ASP.NET MVC 5 site.

I\'m trying to redirect to the Details Action which uses a custom route defined using the new Attribute Rout

相关标签:
2条回答
  • 2020-12-02 13:36

    Moving the AreaRegistration.RegisterAllAreas() to RouteConfig.cs wasn't enough for me. I also needed to use the AreaPrefix parameter for the RouteArea attibute:

    //Use the named parameter "AreaPrefix"
    [RouteArea("AreaName", AreaPrefix = "area-name-in-url")]
    [RoutePrefix("controller-name-in-url")]
    public class SampleController : Controller
    {
        [Route("{actionParameter}")]
        public ActionResult Index(string actionParameter)
        {
            return View();
        }
    }
    

    Edit: At some point, I came across a sample solution from Microsoft that nicely showed how to handle attribute routing. It also showed some nice examples of how to translate a SelectList into an array of input[type="radio"] items as well as doing the same with an array of input[type="checkbox"] items (if I recall). This sample solution is probably a better answer to this question--as well as giving some good examples on displaying radio buttons and checkbox items. If anyone knows of this sample solution, please add a comment with a link to it.

    0 讨论(0)
  • 2020-12-02 13:49

    You are probably combining convention based routing with attribute routing, and you should register your areas after you map the attribute routes.

    The line

    AreaRegistration.RegisterAllAreas();
    

    should be called AFTER this line:

    routes.MapMvcAttributeRoutes();
    

    The explanation (from http://blogs.msdn.com/b/webdev/archive/2013/10/17/attribute-routing-in-asp-net-mvc-5.aspx#route-areas):

    If you are using both Areas with route attributes, and areas with convention based routes (set by an AreaRegistration class), then you need to make sure that area registration happen after MVC attribute routes are configured, however before the default convention-based route is set. The reason is that route registration should be ordered from the most specific (attributes) through more general (area registration) to the mist generic (the default route) to avoid generic routes from “hiding” more specific routes by matching incoming requests too early in the pipeline.

    When you create a blank asp.net mvc website, add an area and start using attribute routing, you will encounter this problem because the "Add Area" action in visual studio adds the RegisterAllAreas call in your Application_Start, before the route configuration..

    Alternative solution

    Perhaps you do not intend to keep using convention based routing and prefer to only use attribute routing. In this case you can just delete the FormsAreaRegistration.cs file.

    0 讨论(0)
提交回复
热议问题