asp.net core 3.1 利用中间件处理options请求

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>

以上也可通过代码控制,可自行搜索

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值