如何启用CORS(JS + MVC Web API) [英] How to enable CORS (JS + MVC Web API)

查看:672
本文介绍了如何启用CORS(JS + MVC Web API)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

On my client side I have this code:

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

然后在我的本地服务器端,我有:

And then on my 'local server' side I have this:

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

            return Email + " : " + Password;
        }

在我的web.config中:

And this in my web.config:

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

我做错了什么?
我总是het这个错误:从外部源不允许。这可以通过启用CORS帮助。

What am I doing wrong? I always het this error: Reading from external source not allowed. This can be helped by enabling CORS.

推荐答案

我遇到这个问题之前,这是我想出了。

I've run into this issue before and here is what I came up with.

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

I created a custom action attribute

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

Now add the attribute to your action This adds the header in so the client does not need to worry about it. I was having an issue using jsonp (which allows cors) and needed so specify my datatype as json

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

        return Email + " : " + Password;
    }

这篇关于如何启用CORS(JS + MVC Web API)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆