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);
        }
      }
  • 相关阅读:
    vue换一换功能原型
    一些文章收集
    mint-ui popup自动关闭
    vue 实现二选一列表
    用数组实现矩阵乘法
    表格
    表单
    django项目创建和结构解释
    js操作元素样式
    操作标签属性
  • 原文地址:https://www.cnblogs.com/liuxiaoji/p/9300907.html
Copyright © 2011-2022 走看看