2016-02-26 164 views
1

我正在尝试为我正在使用WebAPI 2的项目设置CORS。我开始遇到问题,所以我直接从asp.net论坛here创建了一个演示应用程序。一切工作正常,直到我需要使用json作为内容类型。然后我开始得到:Web API 2 Cors请求错误

对预检请求的响应未通过访问控制检查:在请求的资源上没有“Access-Control-Allow-Origin”标头。

我明白这个内容类型发送预检请求,但我傻眼了我怎么能让这个通过。我错过了什么吗?一旦我从AJAX请求中删除“contentType:'application/json'”属性,它就会起作用。

TestController.cs

[Authorize] 
[EnableCors(origins: "*", headers: "*", methods: "*")] 
public class TestController : ApiController 
{ 
    // GET api/<controller> 
    public HttpResponseMessage Get() 
    { 
     return new HttpResponseMessage() 
     { 
      Content = new StringContent("GET: Test message") 
     }; 
    } 

    public HttpResponseMessage Post([FromBody]string name) 
    { 
     return new HttpResponseMessage() 
     { 
      Content = new StringContent("POST: Test message") 
     }; 
    } 

    public HttpResponseMessage Put() 
    { 
     return new HttpResponseMessage() 
     { 
      Content = new StringContent("PUT: Test message") 
     }; 
    } 
} 

WebApiConfig.cs

public static void Register(HttpConfiguration config) 
    { 
     // Web API configuration and services 
     config.EnableCors(); 

     // Web API routes 
     config.MapHttpAttributeRoutes(); 

     config.Routes.MapHttpRoute(
      name: "DefaultApi", 
      routeTemplate: "api/{controller}/{id}", 
      defaults: new { id = RouteParameter.Optional } 
     ); 
    } 

Ajax请求

$.ajax({ 
      type: "POST", 
      url: 'http://localhost:17515/', 
      data: JSON.stringify("Test"), 
      xhrFields: { 
       withCredentials: true 
      }, 
      contentType: "application/json" 
     }); 

enter image description here

enter image description here

+0

[选项405(方法不允许)web api 2]的重复(http://stackoverflow.com/questions/26649361/options-405-method-not-allowed-web-api-2) – Gusman

回答

0

它的客户端将首先发送一个OPTIONS请求到服务器。这个请求,服务器应该加上一个标题:

Access-Control-Allow-Origin: http://localhost:17822 

这表明,在端口17515运行API接受由港口服务的客户端请求17822.

你可以试着改变你的属性:

[EnableCors(origins: "http://localhost:17822", headers: "*", methods: "*")] 

我们还没有使用EnableCors好的经验,所以我们使用OWIN,简单地返回200 OK和手动添加相应的头文件到所有选项请求批准起源发送处理OPTIONS请求。

有CORS上的好文章在MSDN上(可能你已经看到它):https://msdn.microsoft.com/en-us/magazine/dn532203.aspx

0

在你WebApiConfig.cs,你可以尝试启用CORS而不是属性有控制器上。

 var cors = new EnableCorsAttribute("*", "*", "*"); 
     config.EnableCors(cors); 

,而不是仅仅

 config.EnableCors(); 

这工作我在此刻运行一个测试项目。