zoukankan      html  css  js  c++  java
  • 如果调用.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);
        }
      }
  • 相关阅读:
    结构体后面不加 ; 的后果。
    swap的两种错误写法
    rewind和fseek作用分析
    16个get函数的用法。
    枚举的简单使用。
    小知识点
    网线头的做法
    内存和寄存器
    linux下service mongod start启动报错
    appium上下文切换、webview调试以及chromedriver/键盘等报错问题解决
  • 原文地址:https://www.cnblogs.com/liuxiaoji/p/9300907.html
Copyright © 2011-2022 走看看