Skip to main content
 首页 » 编程设计

c#之如何在 ASP.NET WebAPI 项目中使用 MVC 路由

2024年02月27日32sharpest

我有一个 Web API,我想添加一些 asp.net 页面来管理 API 的各个方面。

在 WebApiConfig.cs 文件中,我有几个路由,以下用作 API 的捕获所有路由。

config.Routes.MapHttpRoute(name: "CatchAll",routeTemplate: "{controller}/{action}/{id}",defaults: new { id = RouteParameter.Optional }); 

我想添加一个以/control 为前缀的新部分,以推送到事物的 asp.net 端。为此,我已将以下内容添加到 RouteConfig.cs

    routes.MapRoute( 
        name: "Default", 
        url: "control/{controller}/{action}/{id}", 
        defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } 
    ); 

然后我添加了一个标准 Controller ,我将使用它来管理事物。

public class ManageController : Controller 
{ 
    public ActionResult Index() 
    { 
 
        return Content("Works"); 
    } 
} 

当我在浏览器中访问/control/manage 时,出现以下错误。

No type was found that matches the controller named 'control'

看起来路由被完全绕过,或者充其量,来自 api 路由的 catch all 正在捕获它并给予它优先级。有没有一种方法可以使请求捕获这条路线而无需创建单独的项目?

请您参考如下方法:

注册顺序很重要 您需要注册

public class RouteConfig { 
 
    public static void RegisterRoutes(RouteCollection routes) { 
 
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); 
 
        routes.MapRoute( 
                name: "DefaultMVC", 
                url: "control/{controller}/{action}/{id}", 
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } 
            ); 
        //..other routes. 
    } 
} 

在RouteConfig.cs之前

config.Routes.MapHttpRoute(name: "CatchAll",routeTemplate: "{controller}/{action}/{id}",defaults: new { id = RouteParameter.Optional }); 

在 WebApiConfig.cs 文件中。

在您的情况下,/control/manage url 由 CatchAll 路由处理,从而将控制映射到 Controller 并管理到操作

为了做到这一点,请按以下顺序在 Global.asax 中注册它们:

RouteConfig.RegisterRoutes(RouteTable.Routes); 
GlobalConfiguration.Configure(WebApiConfig.Register);