2

Existed asp.net core Api is look like below

public async Task<IActionResult> UploadAsync()
{
    IFormFile file = null;

    var files = Request.Form.Files;
    if (files.Count > 0)
    {
        file = Request.Form.Files[0];

        var fileText = new StringBuilder();
        using (var reader = new StreamReader(file.OpenReadStream()))
        {
            while (reader.Peek() >= 0)
                fileText.AppendLine(reader.ReadLine());
        }
        int stagingDetailId = await _stagingMarketProvider.GetV1StagingStatusDetailId();


        var result = await SaveStagingMarketsAsync(_fileProvider.ReadImportedMarkets(fileText.ToString()));

        return Ok(result);
    }

    return Ok();

}

Now to consume that api from another asp.net core webapi, I have to pass those files through Request object only, I can't change any existed Api code because of business.

1 Answer 1

1

Solution 1: Applicable if you want your client to get redirected to other API

Assuming the API caller understands HTTP 302 and can act accordingly, the 302 redirect should help you.

public IActionResult Post()
{
    return Redirect("http://file-handler-api/action");
}

From documentation, Redirect method returns 302 or 301 response to client.

Solution 2: C# Code To Post a File Using HttpClient

Below c# code is from this blog post. This is simple code which creates HttpClient object and tries to send the file to a web API.

As you are doing this from one API to another, you will have to save file first at temporary location. That temporary location will be parameter to this method.

Also, After upload you may want to delete the file if it is not required. This private method you can call after file upload to your first API is complete.

private async Task<string> UploadFile(string filePath)
{
    _logger.LogInformation($"Uploading a text file [{filePath}].");
    if (string.IsNullOrWhiteSpace(filePath))
    {
        throw new ArgumentNullException(nameof(filePath));
    }

    if (!File.Exists(filePath))
    {
        throw new FileNotFoundException($"File [{filePath}] not found.");
    }
    using var form = new MultipartFormDataContent();
    using var fileContent = new ByteArrayContent(await File.ReadAllBytesAsync(filePath));
    fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data");
    form.Add(fileContent, "file", Path.GetFileName(filePath));
    form.Add(new StringContent("789"), "userId");
    form.Add(new StringContent("some comments"), "comment");
    form.Add(new StringContent("true"), "isPrimary");

    var response = await _httpClient.PostAsync($"{_url}/api/files", form);
    response.EnsureSuccessStatusCode();
    var responseContent = await response.Content.ReadAsStringAsync();
    var result = JsonSerializer.Deserialize<FileUploadResult>(responseContent);
    _logger.LogInformation("Uploading is complete.");
    return result.Guid;
}

Hope this helps you.

Sign up to request clarification or add additional context in comments.

2 Comments

It seems you didn't understand my problem manoj, Let me elaborate my quetion.
Tried to add another code. This private method you can call from your first API to upload file to other API.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.