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

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

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

GlobalConfiguration.Configure(WebApiConfig.Register);api

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,这一步就是我遗漏掉了的less

<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>spa

加到webserver中server

相关文章
相关标签/搜索