[英]Issue in Enabling CORS for Web API 1, .net 4.0
I need to enable CORS for my Web API and I can't upgrade to Framework 4.5.我需要为我的 Web API 启用 CORS,但我无法升级到 Framework 4.5。 I've tried to add the following to my Web.config to see if it worked, but it didn't:
我尝试将以下内容添加到我的 Web.config 中以查看它是否有效,但没有:
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Accept,Content-Type,X-Requested-With"/>
I am accessing the URL http://localhost:8484/api/values/ from ajax call我正在从 ajax 调用访问 URL http://localhost:8484/api/values/
and getting bellow error并出现以下错误
XMLHttpRequest cannot load http://localhost:8484/api/values .
XMLHttpRequest 无法加载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.
对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。 Origin 'null' is therefore not allowed access.
因此,不允许访问 Origin 'null'。 The response had HTTP status code 405.
响应具有 HTTP 状态代码 405。
I found this simple solution by charanjit singh.我找到了 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
它工作得很好,特别是如果您坚持使用较旧的 Visual Studio 2010 ,在 .Net 4.0 上,当然还有 web api 1。基本上将此功能添加到您的 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
http://www.codeguru.com/csharp/.net/net_asp/using-cross-origin-resource-sharing-cors-in-asp.net-web-api.html
Web API 1.0, you need to enable CORS support using the following statements in the Application_BeginRequest event handler of the Global.asax.cs file. Web API 1.0,您需要在 Global.asax.cs 文件的 Application_BeginRequest 事件处理程序中使用以下语句启用 CORS 支持。
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", allowedOrigin);
Support for CORS can be enabled at three levels.可以在三个级别启用对 CORS 的支持。 These include the following:
这些包括以下内容:
Action level Controller level Global level操作级别 控制器级别 全局级别
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.