[英]Is there a way to avoid http error 405 when uploading a file in asp net core web api?
我有一个 AJAX 表单,它使用 POST 将数据(文件上传)发送到 ASP NET Web API。 我可以毫无问题地点击我的 API 端点并保存文件,然后返回 OK。 当 API 上的执行完成时,我的页面现在显示一个错误,说405 method not allowed 。 我已经配置了 CORS 并允许访问任何来源我也尝试使用禁用安全性的 chrome 上传文件只是为了确保它不是 CORS 但当代码执行没有问题时我仍然得到一个不允许的方法。
下面是我的 AJAX。
<script>
function uploadFiles() {
var fileUpload = $("#files").get(0);
var files = fileUpload.files;
var data = new FormData();
for (var i = 0; i != files.length; i++) {
data.append("files", files[i]);
}
$.ajax({
type: "POST",
url: "@TempData["api"]api/Document/BulkUpload/",
headers: {
'Authorization': 'Bearer @HttpContextAccessor.HttpContext.Session.GetString("token")'
},
contentType: false,
processData: false,
data: data,
async: false,
beforeSend: function () {
//Before sending
},
success: function (messages) {
var list = messages;
$.each(list, function (index, item) {
//alertify.set('notifier', 'position', 'top-center');
//alertify.success('Successfully uploaded the Document');
alert(item);
});
let delay = 5000;
let url = "/Documents";
setTimeout(function () {
location = url;
}, 5000);
},
error: function (e) {
console.log(e.responseText);
if (e.responseText == null) {
e.responseText = "Failed to upload Document. Contact the admin";
}
alertify.set('notifier', 'position', 'top-center');
alertify.error(e.responseText);
},
complete: function () {
//After sending
}
});
}
</script>
下面是我的 API 端点:
[HttpPost]
[Route("BulkUpload")]
public async Task<ActionResult> BulkUpload(IList<IFormFile> files)
{
//Errors
List<string> Errors= new List<string>();
var documents = files;
//Do whatever with the docs
}
以下是我的 CORS 设置:
app.UseCors(x => x
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader());
下面是我的 web.config 文件:
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Methods" value="GET, PUT, POST, DELETE, OPTIONS" />
<add name="Access-Control-Max-Age" value="1000" />
</customHeaders>
</httpProtocol>
</system.webServer>
有什么我做错了吗?
上传成功后,您将当前位置设置为 URL
/文件
似乎相应的端点不支持HTTP GET方法允许。 允许该端点允许的GET方法应该可以解决您的问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.