Skip to main content
 首页 » 编程设计

c#之为 Web API 1、.net 4.0 启用 CORS 时出现问题

2024年02月05日30JustinYoung

我需要为我的 Web API 启用 CORS,但我无法升级到 Framework 4.5。 我试图将以下内容添加到我的 Web.config 中以查看它是否有效,但它没有:

<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 调用

出现以下错误

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

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