如果调用.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
  {
    /// 
    /// Allows incoming POST request to override method type with type specified in header.
    /// 
    /// The  instance this method extends.
    public static IApplicationBuilder UseHttpMethodOverride(this IApplicationBuilder builder)
    {
      if (builder == null)
        throw new ArgumentNullException(nameof (builder));
      return builder.UseMiddleware(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 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

你可能感兴趣的:(如果调用.net core Web API不能发送PUT/DELETE请求怎么办?)