简体   繁体   English

为什么在ASP.NET CORE MVC中应用了错误的路由?

[英]Why wrong routes are getting applied in ASP.NET CORE MVC?

I am working on ASP.NET CORE MVC project. 我正在研究ASP.NET CORE MVC项目。 Which has 2 routes: 其中有2条路线:

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

    routes.MapRoute(
       name: "news",
       template: "News{controller}/{action}");
});

I noticed that in CORE 2.0 Framework the concept of defining specific routes at first do not apply for my 2 routes shown above. 我注意到在CORE 2.0 Framework中,首先定义特定路由的概念不适用于上面显示的我的2条路由。 Is there a Bug? 是否有错误? or there something wrong with my code? 还是我的代码有问题?


When the URL - '/NewsHome/Index' is fetched it is calling the Home Controller Action method. 当获取URL- “ / NewsHome / Index”时 ,它正在调用Home Controller Action方法。

It should actually call the NewsHome Controller's Index method . 实际上应该调用NewsHome Controller的Index方法 What is wrong ? 怎么了 ?

I am also giving an extract from the book - 'Pro ASP.NET Core MVC 2 by Adam Freeman' to make my point. 我还摘录了本书的摘录-“ Adam Freeman的Pro ASP.NET Core MVC 2”,以阐明我的观点。 Please see below: 请看下面:

在此处输入图片说明

what is wrong, please guide me? 有什么问题,请指导我?

The answer is in the screenshot you posted. 答案在您发布的屏幕截图中。 You should reverse the order of the mappings. 您应该颠倒映射的顺序。 In the screenshot it's showing how it would be wrong. 在屏幕截图中,它显示了错误的方式。

It's behaving exactly as explained in the book. 行为与书中所述完全相同。 Just invert the order of your routes. 只需反转您的路线顺序即可。

change 更改

routes.MapRoute(
   name: "news",
   template: "News{controller}/{action}");

TO

routes.MapRoute(
   name: "news",
   template: "/news/{action}");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM