在使用 ASP.Net Web API 4.0 到 4.5 并使用带有 Cors 库的 Web API 2.2 将所有 Web 服务项目升级后,我遇到了同样的问题。我设法成功地解决了这个问题。我所做的是在 App_Start 文件夹的 RouteConfig.cs 文件中消除或注释掉以下语句:`
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
namespace myNameSpace.Configurations
{
public static class RouteConfig
{
public static void Register(HttpConfiguration config)
{
// Web API routes
//DON'T USE THIS. IT WILL GIVE PROBLEMS IN INSTANTIATION OF OBJECTS
//config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "LocationData",
routeTemplate: "dataservices/locations/{controller}/{action}/{id}",
defaults: new {action = "Index", id = RouteParameter.Optional }
);
config.Routes.MapHttpRoute(
name: "ProfileData",
routeTemplate: "dataservices/profiles/{controller}/{action}/{id}",
defaults: new { action = "Index", id = RouteParameter.Optional }
);
config.Routes.MapHttpRoute(
name: "DefaultRoute",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
}
在我的 Global.asax.cs 文件中,我使用的是旧的路由注册
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.Net.Http.Formatting;
using myNameSpace.IoC;
using myNameSpace.Configurations; // Here actually I change the protected void Application_Start() to protected void Configuration() and change the folder to configuration instead on App_Start
using myNameSpace.Controllers.ExceptionSchema;
using myNameSpace.Filters.HttpFilters;
namespace myNameSpace
{
public class WebApiApplication : System.Web.HttpApplication
{
public static void RegisterApis(HttpConfiguration config)
{
config.Filters.Add(new CustomHttpExceptionFilter());
}
protected void Application_Start()
{
//AreaRegistration.RegisterAllAreas();
RegisterApis(GlobalConfiguration.Configuration);
var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
GlobalConfiguration.Configuration.Formatters.Remove(GlobalConfiguration.Configuration.Formatters.XmlFormatter);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.Register(GlobalConfiguration.Configuration);
}
}
}
原因如下:
Web API 2 中的属性路由
注意:从 Web API 1 迁移
在 Web API 2 之前,Web API 项目模板生成的代码如下:
protected void Application_Start()
{
// WARNING - Not compatible with attribute routing.
WebApiConfig.Register(GlobalConfiguration.Configuration);
}
如果启用了属性路由,此代码将引发异常。如果您升级现有 Web API 项目以使用属性路由,请确保将此配置代码更新为以下内容:
protected void Application_Start()
{
// Pass a delegate to the Configure method.
GlobalConfiguration.Configure(WebApiConfig.Register);
}
我正在使用旧路由,我决定不使用属性路由。所以拿出那个声明