如果調用.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);
    }
  }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM