
正文
如果调用.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);
}
}







