问题
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.
- The Order matters. The
areaRoute
should come first. Don't change the order. 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 ofMyAreaName
:Url.Action("actionName", "controllerName", new { Area = "MyAreaName" });
If there's no area named as
MyAreaName
in your project, and you've made the areaoptional
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