gpt4 book ai didi

c# - ASP .NET WebAPI 无法访问路由

转载 作者:行者123 更新时间:2023-11-30 16:51:47 29 4
gpt4 key购买 nike

我有一个基本的 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 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 文件服务器提供。

命中 http://localhost:49706/api/pdffile/upload postman 返回这个:

{ "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' header ”问题?在我看来,这与拥有多台服务器有关,一台用于静态文件服务,另一台用于路由。我想维护此设置。

最佳答案

要允许 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 包。

关于c# - ASP .NET WebAPI 无法访问路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33504732/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com