Webapi Cannot Parse Multipart/Form-Data Post

API controller POST method multipart/form-data using boundary get message inside the body

There isn't built-in support of multi-part/form-data Media Type in .Net5 by default. So, the input formatter should be attached to the MvcBuilder.

Considering the fact that you can't manipulate client-side, ApiMultipartFormDataFormatter which enables this type of input formatting can be utilized.

  1. Add the Package:

Install-Package ApiMultipartFormDataFormatter -Version 3.0.0


  1. Configure the Formatter in Startup.cs

    public void ConfigureServices(IServiceCollection services)
    {
    services.AddControllers(options =>
    {
    options.InputFormatters.Add(new MultipartFormDataFormatter());
    });
    }
  2. Assuming the mentioned well formed json is something like below class:

    public class CustomContent
    {
    public string Name { get; set; }
    }

    So, we need to wrap it up into another class that contains this as a parameter.
    Note: The library doesn't support deserialization by this moment So, a getter-only property is added to the model which returns the deserialized object.

    public class ViewModel
    {
    // Equivalent to ZZZZZZZZZZ
    public string SerializedContent { get; set; }
    public CustomContent Content => !string.IsNullOrEmpty(SerializedContent)
    ? JsonConvert.DeserializeObject<CustomContent>(SerializedContent)
    : null;
    }
  3. Reform the Action to accept the wrapper model.

    [HttpPost]
    [Route("[action]")]
    public IActionResult Parse(ViewModel vm)
    {
    return Ok($"Received Name: {vm?.Content?.Name}");
    }

The working cURL request of the corresponding example is:

curl --location --request POST 'http://localhost:25599/api/MultiPart/Parse' 

\
--header 'Content-Type: multipart/form-data; boundary=boundary' \
--data-raw '--boundary
Content-Disposition: form-data; name="SerializedContent"
Content-Type: application/json
Content-Length: 100

{
"Name" : "Foo"
}
--boundary--'

The response should be equal to Received Name: Foo.

How to set up a Web API controller for multipart/form-data

I normally use the HttpPostedFileBase parameter only in Mvc Controllers. When dealing with ApiControllers try checking the HttpContext.Current.Request.Files property for incoming files instead:

[HttpPost]
public string UploadFile()
{
var file = HttpContext.Current.Request.Files.Count > 0 ?
HttpContext.Current.Request.Files[0] : null;

if (file != null && file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);

var path = Path.Combine(
HttpContext.Current.Server.MapPath("~/uploads"),
fileName
);

file.SaveAs(path);
}

return file != null ? "/uploads/" + file.FileName : null;
}

ASP.NET How read a multipart form data in Web API?

This should help you get started:

 var uploadPath = HostingEnvironment.MapPath("/") + @"/Uploads";
Directory.CreateDirectory(uploadPath);
var provider = new MultipartFormDataStreamProvider(uploadPath);
await Request.Content.ReadAsMultipartAsync(provider);

// Files
//
foreach (MultipartFileData file in provider.FileData)
{
Debug.WriteLine(file.Headers.ContentDisposition.FileName);
Debug.WriteLine("File path: " + file.LocalFileName);
}

// Form data
//
foreach (var key in provider.FormData.AllKeys)
{
foreach (var val in provider.FormData.GetValues(key))
{
Debug.WriteLine(string.Format("{0}: {1}", key, val));
}
}

multipart/form-data post api not working on hcloud

In that action(Post method) i am sending data in string format , on server side(hcloud) url scanner refused the action because some special character.

Now passing the data in josn format, it works fine



Related Topics



Leave a reply



Submit