ajax跨域在某些情况下会发送options请求给服务器,具体情况可自行搜索,如无相关设置会返回405错误
在asp.net core 3.1 webapi下通过中间件来处理options请求
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Microsoft.AspNetCore.Builder
{
public class OptionsRequestMiddleware
{
private readonly RequestDelegate _next;
public OptionsRequestMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext context)
{
if (context.Request.Method.ToUpper() == "OPTIONS")
{
context.Response.StatusCode = 200;
return;
}
await _next.Invoke(context);
}
}
/// <summary>
/// 扩展中间件
/// </summary>
public static class OptionsRequestMiddlewareExtensions
{
public static IApplicationBuilder UseOptionsRequest(this IApplicationBuilder app)
{
return app.UseMiddleware<OptionsRequestMiddleware>();
}
}
}
在Startup.cs里面的Configure中加上
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
...
app.UseOptionsRequest();
...
}
web.config配置如下
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<!-- To customize the asp.net core module uncomment and edit the following section.
For more info see https://go.microsoft.com/fwlink/?linkid=838655 -->
<system.webServer>
<handlers>
<remove name="aspNetCore" />
<add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModule" resourceType="Unspecified" />
</handlers>
<aspNetCore processPath="C:\Program Files\dotnet\dotnet.exe" arguments="Zzwl.Web.dll" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" />
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Methods" value="*" />
<add name="Access-Control-Allow-Headers" value="*" />
</customHeaders>
</httpProtocol>
</system.webServer>
</configuration>
以上也可通过代码控制,可自行搜索