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);
        }
    }

    /// 
    /// 扩展中间件
    /// 
    public static class OptionsRequestMiddlewareExtensions
    {
        public static IApplicationBuilder UseOptionsRequest(this IApplicationBuilder app)
        {
            return app.UseMiddleware();
        }
    }
}

在Startup.cs里面的Configure中加上 

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            ...

            app.UseOptionsRequest();

            ...
        }

web.config配置如下




  
  
  
    
      
      
    
    
        
            
                
                
                
            
        
  
  

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

你可能感兴趣的:(asp.net,c#,asp.net)