weixin_33705053 2016-02-26 21:41 采纳率: 0%
浏览 36

Web API 2 Cors请求错误

I am trying to get CORS set up for a project I am working on with WebAPI 2. I started having issues, so I created a demo app directly from asp.net forums here. Everything was working correctly until I needed to use json as the content type. Then I started getting:

Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

I understand with this content type sends preflight requests, but I am dumbfounded how I can get this to pass. Am I missing something? As soon as I remove the "contentType: 'application/json'" attribute from AJAX request, it works.

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 Request

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

  • 写回答

2条回答 默认 最新

  • weixin_33675507 2016-02-26 21:55
    关注

    It client will first send an OPTIONS request to the server. To this request, the server should add a header:

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

    This indicates that the API running on port 17515 accepts requests from the client served by port 17822.

    You could try changing your attribute to:

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

    We haven't had good experiences using EnableCors, so we handle OPTIONS requests using OWIN, simply returning 200 OK and manually adding the appropriate headers to all OPTIONS request sent by approved origins.

    There is a good article on CORS on MSDN (likely you have already seen it): https://msdn.microsoft.com/en-us/magazine/dn532203.aspx

    评论

报告相同问题?

悬赏问题

  • ¥15 计算二重积分∫∫e^(x+y)dxdy,其中0≤x≤1,0≤y≤1,试分别用复合辛普森公式(取n=4)以及高斯求积公式(取n=4)计算积分 给出matlab程序
  • ¥15 opencv 无法读取视频
  • ¥15 用matlab 实现通信仿真
  • ¥15 按键修改电子时钟,C51单片机
  • ¥60 Java中实现如何实现张量类,并用于图像处理(不运用其他科学计算库和图像处理库))
  • ¥20 5037端口被adb自己占了
  • ¥15 python:excel数据写入多个对应word文档
  • ¥60 全一数分解素因子和素数循环节位数
  • ¥15 ffmpeg如何安装到虚拟环境
  • ¥188 寻找能做王者评分提取的