c# - 无法在 MVC 项目中访问 Web API 2 Controller

标签 c# asp.net-web-api asp.net-web-api2 asp.net-web-api-routing

我无法使用我在 MVC 项目中使用 ASP.Net Web API 2 Controller 编写的 API。

enter image description here

localhost:57323/api/billpayment/getbillers/10 有效,但 localhost:57323/api/billpayment/getbillers 无效。

WebAPI.config

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.MapHttpAttributeRoutes();

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

Global.asax

public class MvcApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);
        GlobalConfiguration.Configure(WebApiConfig.Register);
    }
}

最佳答案

由于路由的配置方式,您遇到了路由冲突。

Web API 路由需要在标准 MVC 路由之前添加到路由表中。

更新

public class MvcApplication : System.Web.HttpApplication {
    protected void Application_Start() {
        AreaRegistration.RegisterAllAreas();
        GlobalConfiguration.Configure(WebApiConfig.Register); //<-- This MUST come before
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes); //<-- THIS to avoid conflicts
        BundleConfig.RegisterBundles(BundleTable.Bundles);        
    }
}

关于c# - 无法在 MVC 项目中访问 Web API 2 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51592179/

相关文章:

c# - Microsoft Azure 中的 SQL 连接错误

asp.net-web-api2 - 从服务器手动过期 JWT token - WEB API 2

c# - 在 Entity Framework 支持的 Web API 2 POST 调用中返回一个对象以及 409 冲突错误?

c# - 如何测量 WPF Silverlight FPS 或渲染时间?

validation - .NET Web API 2 OWIN Bearer Token Authentication 直接调用

asp.net-mvc - MVC Web Api - 准系统最小项目结构

c# - asp web api补丁实现

c# - wpf TimeSpanUpDown 首先增加秒数

c# - 无法创建抽象类?

c# - 使用 C# 在 Windows 8 上获取当前线程 ID