Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET Core 2: How to check if the request is MIME multipart Content?

In ASp.NET MVC, you can check if the current request is MIME multipart content. How to check that in .NET Core? I have an action filter to validate that, but not sure how to evaluate to request header. IsMimeMultipartContent is not available in .NET Core.

/// <summary>
/// Checks whether the current request specified content is MIME multipart content.
/// </summary>
/// <exception cref="HttpRequestException">Raised when the current request doesn't have MIME multipart content.</exception>
public class HasMimeMultipartContentAttribute : ActionFilterAttribute
{
    public override void OnResultExecuting(ResultExecutingContext context)
    {
        if (!context.HttpContext.Request.Headers.IsMimeMultipartContent())
            throw new HttpRequestException("This request does not contain any file to upload.");
    }
}
like image 848
Saeid Avatar asked Aug 24 '17 21:08

Saeid


People also ask

What is IFormFile C#?

What is IFormFile. ASP.NET Core has introduced an IFormFile interface that represents transmitted files in an HTTP request. The interface gives us access to metadata like ContentDisposition, ContentType, Length, FileName, and more. IFormFile also provides some methods used to store files.

What is multipart content type?

The multipart/byteranges content type is defined as a part of the HTTP message protocol. It includes two or more parts, each with its own Content-Type and Content-Range fields. The parts are separated using a MIME boundary parameter.

What is FromForm?

The FromForm attribute is for incoming data from a submitted form sent by the content type application/x-www-url-formencoded while the FromBody will parse the model the default way, which in most cases are sent by the content type application/json , from the request body.

What is ReadAsMultipartAsync?

ReadAsMultipartAsync<T>(HttpContent, T) Reads all body parts within a MIME multipart message and produces a set of HttpContent instances as a result using the streamProvider instance to determine where the contents of each body part is written. ReadAsMultipartAsync<T>(HttpContent, T, CancellationToken)


1 Answers

ASP.NET MVC Core uses the IFormFile interface to bind multipart HTTP requests. If the request does not use multipart/form-data, the documentation states that the bound value will be null.

like image 100
Mathieu Renda Avatar answered Sep 22 '22 07:09

Mathieu Renda