简体   繁体   中英

Pass files to another asp.net core webapi from another webapi

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM