ASP .NET WebAPI 无法访问路由

ASP .NET WebAPI can't access route

我有一个基本的 ASP .NET WebAPI 项目。有一个PdfFileController:

[RoutePrefix("api/pdffile")]
public class PdfFileController : ApiController
{
    [HttpPost]
    [Route("upload")]
    public async Task<dynamic> Upload(dynamic uploadedData)
    {
        List<object> files = uploadedData.pdfs;
        // ...
    }
}

在客户端我有一个 POST 请求使用 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);
});

POST 请求 URL 解析为 http://localhost:49706/api/pdffile/upload。根据此请求,我收到此消息:

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.

我的静态 html 和 js 文件由位于 localhost:8000 的本地简单 python 文件服务器提供。

用 Postman http://localhost:49706/api/pdffile/upload 命中 returns 这个:

{ "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)" }

所以这里可能存在几个问题。我的问题是我必须怎么做才能克服 "No 'Access-Control-Allow-Origin' header is present" 问题?在我看来,这与拥有多台服务器有关,一台用于静态文件服务,另一台用于路由。我想保持这个设置。

要允许 CORS(跨域请求),请尝试在您的 webapiconfig 中指定。cs/Register

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        var cors = new EnableCorsAttribute("www.example.com", "*", "*");
        config.EnableCors(cors);
        // ...
    }
}

这需要 Microsoft.AspNet.Cors NuGet 包。