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

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

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>节点中

坑4:注意,如果请求的header有Authorization或者其他的值这个千万不能过长,太长了也会提示!!

posted @ 2020-06-23 08:58  码路迢迢  阅读(688)  评论(0编辑  收藏  举报