关于.net mvc webapi跨域设置的坑

本人采用的是MVC5+webapi2.X版本作为代码基础框架,在跨域时遇到了一些细节的坑,前端一直访问提示跨域问题,最后解决了,总体正确的方法总共核心配置的地方有3个,故分享和记录一下:

1:Global全局启动类中一定要加上这句话

GlobalConfiguration.Configure(WebApiConfig.Register);

2:WebApiConfig.cs

public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
//跨域配置
config.EnableCors(new EnableCorsAttribute("*", "*", "*"));
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "ActionApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional });
}
}

3:Web.config,这一步就是我遗漏掉了的

<handlers>
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<remove name="OPTIONSVerbHandler" />
<remove name="TRACEVerbHandler" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>

加到webserver中

原文地址:https://www.cnblogs.com/coder-lc/p/13180241.html