如果调用.net core Web API不能发送PUT/DELETE请求怎么办?

通过阅读大佬的文章 http://www.cnblogs.com/artech/p/x-http-method-override.html
想到的 通过注册中间件来解决这个问题

  public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            app.UseHttpMethodOverride();
        }
  public static class HttpMethodOverrideExtensions
  {
    /// <summary>
    /// Allows incoming POST request to override method type with type specified in header.
    /// </summary>
    /// <param name="builder">The <see cref="T:Microsoft.AspNetCore.Builder.IApplicationBuilder" /> instance this method extends.</param>
    public static IApplicationBuilder UseHttpMethodOverride(this IApplicationBuilder builder)
    {
      if (builder == null)
        throw new ArgumentNullException(nameof (builder));
      return builder.UseMiddleware<HttpMethodOverrideMiddleware>(Array.Empty<object>());
    }
  }
  public class HttpMethodOverrideMiddleware
  {
    private const string xHttpMethodOverride = "X-Http-Method-Override";
    private readonly RequestDelegate _next;
    private readonly HttpMethodOverrideOptions _options;

    public HttpMethodOverrideMiddleware(RequestDelegate next, IOptions<HttpMethodOverrideOptions> options)
    {
      if (next == null)
        throw new ArgumentNullException(nameof (next));
      if (options == null)
        throw new ArgumentNullException(nameof (options));
      this._next = next;
      this._options = options.Value;
    }

    public async Task Invoke(HttpContext context)
    {
      if (string.Equals(context.Request.Method, "POST", StringComparison.OrdinalIgnoreCase))
      {
        if (this._options.FormFieldName != null)
        {
          if (context.Request.HasFormContentType)
          {
            StringValues stringValues = (await context.Request.ReadFormAsync(new CancellationToken()))[this._options.FormFieldName];
            if (!string.IsNullOrEmpty((string) stringValues))
              context.Request.Method = (string) stringValues;
          }
        }
        else
        {
          StringValues header = context.Request.Headers["X-Http-Method-Override"];
          if (!string.IsNullOrEmpty((string) header))
            context.Request.Method = (string) header;
        }
      }
      await this._next(context);
    }
  }

 

转载于:https://www.cnblogs.com/liuxiaoji/p/9300907.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值