在为Web API 1,.net 4.0启用CORS时出现问题 [英] Issue in Enabling CORS for Web API 1, .net 4.0
问题描述
我需要为我的Web API启用CORS,并且不能升级到Framework 4.5. 我试图将以下内容添加到我的Web.config中,以查看它是否有效,但没有成功
I need to enable CORS for my Web API and I can't upgrade to Framework 4.5. I've tried to add the following to my Web.config to see if it worked, but it didn't:
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Accept,Content-Type,X-Requested-With"/>
我正在从以下位置访问URL http://localhost:8484/api/values/ ajax呼叫
I am accessing the URL http://localhost:8484/api/values/ from ajax call
并出现以下错误
XMLHttpRequest无法加载 http://localhost:8484/api/values .对预检请求的响应未通过访问控制检查:在所请求的资源上不存在"Access-Control-Allow-Origin"标头.因此,不允许访问原始空".响应的HTTP状态码为405.
XMLHttpRequest cannot load http://localhost:8484/api/values. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. The response had HTTP status code 405.
推荐答案
我通过charanjit singh找到了这个简单的解决方案. 如果您对旧的Visual Studio 2010,.Net 4.0以及Web api 1有所了解,它的效果特别好. 基本上将此功能添加到您的Global.asax.cs
I found this simple solution by charanjit singh. It worked nicely especially if you are stuck with older visual studio 2010 , on .Net 4.0 and of course web api 1. Basically add this function to your Global.asax.cs
protected void Application_BeginRequest(object sender, EventArgs e)
{
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
{
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods",
"GET, POST, PUT, DELETE");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers",
"Content-Type, Accept");
HttpContext.Current.Response.End();
}
}
ref. links: note you must scroll to the bottom comments for the answer. http://www.codeguru.com/csharp/.net/net_asp/using-cross-origin-resource-sharing-cors-in-asp.net-web-api.html
这篇关于在为Web API 1,.net 4.0启用CORS时出现问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!