Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/290.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# ASP.NET MVC服务路由覆盖默认路由_C#_Asp.net Mvc_Asp.net Mvc 5 - Fatal编程技术网

C# ASP.NET MVC服务路由覆盖默认路由

C# ASP.NET MVC服务路由覆盖默认路由,c#,asp.net-mvc,asp.net-mvc-5,C#,Asp.net Mvc,Asp.net Mvc 5,我已将WCF服务添加到MVC 5应用程序中,并为其创建了一条路由: public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.Add(new ServiceRoute("Service1.svc", new ServiceHostFactory(), typeof(Service1))); rout

我已将WCF服务添加到MVC 5应用程序中,并为其创建了一条路由:

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
    routes.Add(new ServiceRoute("Service1.svc", new ServiceHostFactory(), typeof(Service1)));
    routes.MapRoute(
        name: "Default",
        url: "{controller}/{action}/{id}",
        defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
    );
}
问题是我的所有链接现在都指向Service1.svc路由
@Html.ActionLink(“Passport Maker”、“Index”、“Home”、new{area=”“}、new{@class=“navbar brand”})
变成
http://localhost:50099/Service1.svc?action=Index&controller=Home
和其他链接也会以同样的方式更改

如果在“默认”路由之后添加ServiceRoute,则链接可以正常工作,但服务不可用

为什么会发生这种情况(链接中没有“Service1”,为什么他们会选择服务路由?)以及如何修复它?

解决方案:

routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
    constraints: new { controller = "^(?!Service1.svc).*" }
);

routes.Add(new ServiceRoute("Service1.svc", new ServiceHostFactory(), typeof(Service1)));
对可能遇到类似问题的人的解释:问题的原因是
Html.ActionLink
使用第一个匹配路径生成链接。我的服务路由是第一个并且是匹配的,因为路由不需要包含要匹配的
{controller}
{action}
参数(正如我最初所想的那样)


解决方案是将默认路由放在第一位,因此
Html.ActionLink
使用它。为了仍然能够使用服务路由,需要使用约束将其从第一个路由中排除。regex
^(?!Service1.svc)。*
只匹配那些不以“Service1.svc”开头的控制器名称。

请参阅此[链接][1],这将有助于解决您的问题。[1] :@JineshJain谢谢,它指引我走上正确的道路。