3

I want to send an image with C# HttpClient, receive it in ASP.NET Core controller and save it to disk. I tried various methods but all i'm getting in controller is null reference.

My http client:

public class HttpClientAdapter
{
    private readonly HttpClient _client;

    public HttpClientAdapter()
    {
        _client = new HttpClient();
    }

    public async Task<HttpResponse> PostFileAsync(string url, string filePath)
    {
        var requestContent = ConstructRequestContent(filePath);
        var response = await _client.PostAsync(url, requestContent);
        var responseBody = await response.Content.ReadAsStringAsync();

        return new HttpResponse
        {
            StatusCode = response.StatusCode,
            Body = JsonConvert.DeserializeObject<JObject>(responseBody)
        };
    }

    private MultipartFormDataContent ConstructRequestContent(string filePath)
    {
        var content = new MultipartFormDataContent();
        var fileStream = File.OpenRead(filePath);
        var streamContent = new StreamContent(fileStream);
        var imageContent = new ByteArrayContent(streamContent.ReadAsByteArrayAsync().Result);
        imageContent.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data");
        content.Add(imageContent, "image", Path.GetFileName(filePath));
        return content;
    }
}

and controller:

[Route("api/files")]
public class FilesController: Controller
{
    private readonly ILogger<FilesController> _logger;

    public FilesController(ILogger<FilesController> logger)
    {
        _logger = logger;
    }

    [HttpPost]
    public IActionResult Post(IFormFile file)
    {

        _logger.LogInformation(file.ToString());
        return Ok();
    }
}

As i mentioned above, the IFormFile object i'm getting in the controller is null reference. I tried adding [FromBody], [FromForm], tried creating class with two properties: one of type string and one with type IFormFile, but nothing works. Also instead of sending file with C# HttpClient i used Postman - same thing happens.

Does anyone know solution for this problem? Thanks in advance.

kubi
  • 897
  • 2
  • 9
  • 23
  • 1
    Possible duplicate of [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Brian Jul 24 '18 at 20:42
  • That's not what i was asking about – kubi Jul 26 '18 at 18:38

1 Answers1

3

The name of the form field must match the property name:

content.Add(imageContent, "file", Path.GetFileName(filePath));

file instead of image, since you use file in

public IActionResult Post(IFormFile file)
{
}
huysentruitw
  • 27,376
  • 9
  • 90
  • 133