Instantly share code, notes, and snippets.

Embed
What would you like to do?
Multipart Content-Type request results in IOException
using Microsoft.AspNetCore.Builder;
namespace MvcBug
{
public static class RequestValidatorExtensions
{
// Extensions method to simplify RequestValidatorMiddleware usage
public static IApplicationBuilder UseRequestValidator(this IApplicationBuilder app)
{
return app.UseMiddleware<RequestValidatorMiddleware>();
}
}
}
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
namespace MvcBug
{
public class RequestValidatorMiddleware
{
private readonly RequestDelegate _next;
public RequestValidatorMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext context)
{
// Check if request body is empty and it's a multipart request
if (context.Request.ContentLength == 0
&& context.Request.ContentType != null
&& context.Request.ContentType.ToUpper().StartsWith("MULTIPART/"))
{
// Set 400 response with a message
context.Response.StatusCode = StatusCodes.Status400BadRequest;
await context.Response.WriteAsync("Multipart request body must not be empty.");
}
else
{
// All other requests continue the way down the pipeline
await _next(context);
}
}
}
}
// Blog post: https://ignas.me/tech/multipart-content-type-request-ioexception/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
namespace MvcBug
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
// Check for invalid HTTP requests before the MVC
app.UseRequestValidator();
// Let MVC process other requests
app.UseMvc();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment