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

528 IT屋

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

And this in my web.config:

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

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

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

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



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

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

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

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


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



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

return Email +":"+密码;
}


在我的web.config中:



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


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


解决方案

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



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



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

public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
{
actionExecutedContext.Response.Headers.Add("Access Control -Allow-Origin","*");
//注意"*"将允许所有 - 您可以将其更改为只允许tursted域
}
}


现在添加属性到您的操作
这增加了头,所以客户端不需要担心它。我有一个问题使用jsonp(它允许cors)和需要这样指定我的数据类型为json



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

return Email +":"+密码;
}

本文地址:IT屋 » 如何启用CORS(JS + MVC Web API)