因此,我想在.net Web API上启用CORS,但是客户端应用程序会继续获得404的选项请求和第二个错误:
Has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: it does not have http ok status
我已逐步遵循Microsoft网站的概述,但仍然没有成功。
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Added this line to my WebApiConfig.cs file
var cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(cors);
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
I also tried it by adding the headers in the Web.config in the httpProtocol tag file like so:
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="*" />
<add name="Access-Control-Allow-Methods" value="*" />
</customHeaders>
</httpProtocol>
答案 0 :(得分:1)
Try to enable from the web.config file under <system.webserver></system.webserver> like so:
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Credentials" value="true"/>
<add name="Access-Control-Allow-Headers" value="Content-Type" />
<add name="Access-Control-Allow-Methods" value="GET, POST, PUT, OPTIONS" />
</customHeaders>
</httpProtocol>
To handle the preflight request error add the line below in the <handlers></handlers> tags:
<add name="OPTIONSVerbHandler" path="*" verb="OPTIONS" modules="ProtocolSupportModule" requireAccess="None" responseBufferLimit="4194304" />
Then in the Global.asax file, add the following method:
protected void Application_BeginRequest(object sender, EventArgs e)
{
if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
{
HttpContext.Current.Response.Flush();
}
}
答案 1 :(得分:0)
尝试一下:
public static void Register(HttpConfiguration config)
{
config.EnableCors();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
在您的api controller
中:
[EnableCors(origins: "*", headers: "*", methods: "*")]
public class TestController : ApiController
{
}
如果要按操作方法启用它,请执行以下操作:
[EnableCors(origins: "*", headers: "*", methods: "*")]
public HttpResponseMessage Get() { ... }