2014-09-28 36 views
0

在我的客户端我有这样的代码:如何启用CORS(JS + MVC的Web API)

<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来帮助。

+0

我想你也需要数据类型:“JSONP” – 2014-09-28 11:57:40

+0

您是否尝试过使用cors属性上的控制器? '[EnableCors(“*”,“*”,“*”)]'? – Stefan 2014-09-28 12:03:49

+0

两人仍然给我失败。 – 2014-09-28 16:15:37

回答

0

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

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

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