Area is not passed to Url.Action() in ASP.net Core

爷,独闯天下 提交于 2021-01-29 05:25:24

问题


The following code is working in normal ASP.net MVC.

Url.Action("actionName", "controllerName", new { Area = "areaName" });

But it is not work well in ASP.net Core. Area is recognized as a query string parameter.

How can I solve it? Thanks for any help.


回答1:


Make sure you're registering routes as below :

app.UseMvc(routes =>
{
    routes.MapRoute(
        name: "areaRoute",
        // if you don't have such an area named as `areaName` already, 
        //    don't make the part of `{area}` optional by `{area:exists}`
        template: "{area}/{controller=Home}/{action=Index}");  

    routes.MapRoute(
        name: "default",
        template: "{controller=Home}/{action=Index}/{id?}");
});

I could reproduce the same issue as yours by changing the order of routes, or by changing the {area} to be optional.

  1. The Order matters. The areaRoute should come first. Don't change the order.
  2. When generating url to an area, if you don't have such an area already, don't change the part of {area} to be optional by {area:exists}. For example, let's say you're trying to generate a url to area of MyAreaName:

    Url.Action("actionName", "controllerName", new { Area = "MyAreaName" });
    

    If there's no area named as MyAreaName in your project, and you've made the area optional by:

    routes.MapRoute(
        name: "areaRoute",
        template: "{area:exists}/{controller=Home}/{action=Index}");
    

    the generated url will be controllerName/actionName?Area=MyAreaName.



来源:https://stackoverflow.com/questions/53140541/area-is-not-passed-to-url-action-in-asp-net-core

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!