CORS Post request works locally, but not on the server

I have two projects in one solution. One is an ASP.NET MVC project, and the other is a web API project. On my local machine, the MVC project is working on. http://localhost:2302/I enabled CORS in the Web API project using the following code in the WebApiConfig.cs file:

namespace WebServices
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            var cors = new EnableCorsAttribute("http://localhost:2302", "*", "*");
            config.EnableCors(cors);
            config.MapHttpAttributeRoutes();
            config.Routes.MapHttpRoute("ActionApi", "{controller}/{action}/");
        }
    }
}

I also have a controller where I have a controller, for example:

namespace WebServices.Controllers
{
    public class UploadController : ApiController
    {
        private readonly IUploadManager _uploadManager;

        public UploadController(IUploadManager uploadManager)
        {
            _uploadManager = uploadManager;
        }

        [HttpPost]
        public async Task<HttpResponseMessage> UploadImage()
        {
            var result = await _uploadManager.UploadImage(Request);

            return result.Success
                ? Request.CreateResponse(HttpStatusCode.OK, result)
                : Request.CreateResponse(HttpStatusCode.Conflict);
        }
    }
}

The UploadImage method exists inside the repository class, where there is upload logic. Finally, I call my service using the XMLHttpRequest JavaScript object as follows:

var xhr = new window.XMLHttpRequest();
var uploadPercent;

xhr.upload.addEventListener('progress', function (event) {
    var percent = Math.floor((event.loaded / event.total) * 100);
    uploadPercent = percent;
}, false);

xhr.onreadystatechange = function (event) {
    if (event.target.readyState === event.target.DONE) {
        if (event.target.status !== 200) {
            console.log('error in uploading image');
        } else {
            var status = JSON.parse(event.target.response);
            var imageGuid = status.returnId;
            var imageUrl = status.returnString;
        }
     }
};

xhr.open('post', 'http://localhost:4797/Upload/UploadImage', true);
var data = new FormData();
var files = $('#uploadInput')[0].files;

for (var i = 0; i < files.length; i++) {
    data.append('file' + i, files[i]);
}

xhr.send(data);

, . , (, - , ). OPTIONS, 400 Bad Request. , . , :

Accept:*/*
Accept-Encoding:gzip, deflate, sdch
Accept-Language:en-US,en;q=0.8,el;q=0.6
Access-Control-Request-Headers:content-type
Access-Control-Request-Method:POST
Connection:keep-alive
Host:api.example.com
Origin:http://example.com
Referer:http://example.com/Account/ExtraDetails/91a832ee-496c-46a7-ac4b-dfb89bbc8fc5
User-Agent:Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36

:

Cache-Control:no-cache
Content-Length:69
Content-Type:application/json; charset=utf-8
Date:Mon, 15 Dec 2014 22:42:11 GMT
Expires:-1
Pragma:no-cache
Server:Microsoft-IIS/7.5
X-AspNet-Version:4.0.30319
X-Powered-By:ASP.NET

, Access-Control-Allow-Origin, , . - , - ? .

+4
1

, Options.

Web API Options, , CORS.

, , , . , :

protected void Application_BeginRequest()
{
    if (Request.Headers.AllKeys.Contains("Origin") && Request.HttpMethod == "OPTIONS")
    {
        Response.Flush();
    }
}

, , APIs, GET POST, . , DELETE API, . , .

Cors web.config config.EnableCors(cors);

<httpProtocol>
  <customHeaders>
    <add name="Access-Control-Allow-Origin" value="*" />
    <add name="Access-Control-Allow-Headers" value="Content-Type" />
    <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
  </customHeaders>
 </httpProtocol>

, , *. , * .

+2

All Articles