ASP .NET WebAPI 无法访问路由。

3

我有一个基本的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;
        // ...
    }
}

而在客户端方面,我使用Oboe进行POST请求:

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不能加载http://localhost:49706/api/pdffile/upload。 对预检请求的响应未能通过访问控制检查:所请求的资源上没有'Access-Control-Allow-Origin'头。 因此,源“null”不允许访问。响应HTTP状态代码为405。

我的静态HTML和JS文件是通过本地简单的Python文件服务器提供服务的,位于localhost:8000。
使用Postman访问http://localhost:49706/api/pdffile/upload返回如下内容:

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

因此,这里可能有几个问题。我的问题是我必须做什么才能解决“未提供'Access-Control-Allow-Origin'头”的问题?我觉得这似乎与具有多个服务器有关,一个用于静态文件服务,另一个用于路由。我想要保持这种设置。

你可能需要在服务器应用程序上启用CORS - Matias Cicero
1个回答

2

为了允许跨域请求(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包。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接