【问题标题】:How to enable CORS (JS + MVC Web API)如何启用 CORS (JS + MVC Web API)
【发布时间】:2014-11-22 22:37:17
【问题描述】:

在我的客户端我有这个代码:

<script>
    function SignIn() {
        $.ajax({

            type: 'GET',
            url: 'http://localhost:54976/api/values?email=dieter&password=borgers',
            contentType: 'text/plain',
            beforeSend: function (xhr) {
                xhr.setRequestHeader('Access-Control-Allow-Origin', '*');
            },
            //data: parameters,
            crossDomain: true,
            xhrFields: {
                withCredentials: false
            },

            headers: {
                'Access-Control-Allow-Origin': '*'
            },

            success: function (data) {
                alert(data);
            },

            error: function () {
                alert("fail");
            }
        });
    }
</script>

然后在我的“本地服务器”端我有这个:

public string Get(string Email, string Password)
        {
            Request.Headers.Add("Access-Control-Allow-Origin", "*");

            return Email + " : " + Password;
        }

这在我的 web.config 中:

<httpProtocol>
  <customHeaders>
    <add name="Access-Control-Allow-Origin" value="*" />
  </customHeaders>
</httpProtocol>

我做错了什么? 我总是遇到这个错误:不允许从外部源读取。这可以通过启用 CORS 来帮助解决。

【问题讨论】:

  • 我觉得你还需要dataType: "jsonp"
  • 您是否尝试过在控制器上使用 Cors 属性? [EnableCors("*", "*", "*")]?
  • 两者仍然给我一个失败。
  • 您使用的是哪个版本的 Web Api?
  • ID:Microsoft.AspNet.WebApi

标签: javascript c# asp.net-mvc cors


【解决方案1】:

我之前遇到过这个问题,这就是我想出的。

我创建了一个自定义操作属性

public class AllowCrossDomain : System.Web.Http.Filters.ActionFilterAttribute
{

    public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
    {
        actionExecutedContext.Response.Headers.Add("Access-Control-Allow-Origin", "*");
//Note "*" will allow all - you can change this to only allow tursted domains
    }
}

现在将属性添加到您的操作中 这会添加标头,因此客户端无需担心它。我在使用 jsonp(允许 cors)时遇到问题,需要将我的数据类型指定为 json

[AllowCrossDomain]
public string Get(string Email, string Password)
    {
        Request.Headers.Add("Access-Control-Allow-Origin", "*");

        return Email + " : " + Password;
    }

【讨论】:

    猜你喜欢
    • 2017-02-08
    • 2017-05-03
    • 2021-09-30
    • 2017-12-16
    • 2016-05-11
    • 2013-09-08
    • 2014-10-20
    • 2016-01-02
    • 2019-08-10
    相关资源
    最近更新 更多