问题描述
我需要为我的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
并出现以下错误
推荐答案
我通过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();
}
}
参考链接:请注意,您必须滚动至底部注释才能找到答案. http://www.codeguru.com/csharp/.net/net_asp/using-cross-origin-resource-sharing-cors-in-asp.net-web-api.html
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时出现问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!