Reputation: 6694
I have a basic ASP .NET WebAPI project. There is a PdfFileController
:
[RoutePrefix("api/pdffile")]
public class PdfFileController : ApiController
{
[HttpPost]
[Route("upload")]
public async Task<dynamic> Upload(dynamic uploadedData)
{
List<object> files = uploadedData.pdfs;
// ...
}
}
And on the client side I have a POST request using Oboe:
oboe({
url: this.props.configuration.rootApiUrl + 'pdffile/upload',
method: 'POST',
body: { pdfs: pdfs }
}).node('pdfsAsImages.*', function(pdf){ // This callback will be called every time a new pdf image comes in
channel.pub('pdf.converted', pdf);
});
The POST request URL resolves to http://localhost:49706/api/pdffile/upload. From this request, I receive this message:
OPTIONS http://localhost:49706/api/pdffile/upload
XMLHttpRequest cannot load http://localhost:49706/api/pdffile/upload. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. The response had HTTP status code 405.
My static html and js files are being served from a local simple python file server at localhost:8000.
Hitting http://localhost:49706/api/pdffile/upload with Postman returns this:
{ "Message": "The request entity's media type 'multipart/form-data' is not supported for this resource.", "ExceptionMessage": "No MediaTypeFormatter is available to read an object of type 'Object' from content with media type 'multipart/form-data'.", "ExceptionType": "System.Net.Http.UnsupportedMediaTypeException", "StackTrace": " at System.Net.Http.HttpContentExtensions.ReadAsAsync[T](HttpContent content, Type type, IEnumerable`1 formatters, IFormatterLogger formatterLogger, CancellationToken cancellationToken)\r\n at System.Web.Http.ModelBinding.FormatterParameterBinding.ReadContentAsync(HttpRequestMessage request, Type type, IEnumerable`1 formatters, IFormatterLogger formatterLogger, CancellationToken cancellationToken)" }
So there may be several issues going on here. My question is what must I do to overcome the "No 'Access-Control-Allow-Origin' header is present" problem? It seems to me it has something to do with having the multiple servers, one for static file serving and one for routes. I want to maintain this setup.
Upvotes: 3
Views: 2608
Reputation: 514
To allow CORS (cross domain request) try specifying in your webapiconfig.cs/Register
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
var cors = new EnableCorsAttribute("www.example.com", "*", "*");
config.EnableCors(cors);
// ...
}
}
This requires the Microsoft.AspNet.Cors NuGet package.
Upvotes: 2