【问题标题】:Pass files to another asp.net core webapi from another webapi将文件从另一个 webapi 传递到另一个 asp.net core webapi
【发布时间】:2020-02-15 18:42:41
【问题描述】:

现有的 asp.net core Api 如下所示

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();

}

现在要从另一个 asp.net 核心 webapi 使用该 api,我必须仅通过 Request 对象传递这些文件,由于业务原因,我无法更改任何现有的 Api 代码。

【问题讨论】:

    标签: c# asp.net-core httprequest httpclient asp.net-core-webapi


    【解决方案1】:

    解决方案 1:如果您希望您的客户端被重定向到其他 API,则适用

    假设 API 调用者理解 HTTP 302 并可以采取相应的行动,302 redirect 应该可以帮助您。

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

    documentation,Redirect 方法返回 302 或 301 响应给客户端。

    解决方案 2:使用 HttpClient 发布文件的 C# 代码

    以下c#代码来自this blog post。这是创建 HttpClient 对象并尝试将文件发送到 Web API 的简单代码。

    当您从一个 API 到另一个 API 执行此操作时,您必须先将文件保存在临时位置。该临时位置将成为此方法的参数。

    此外,上传后,如果不需要,您可能需要删除文件。在文件上传到您的第一个 API 完成后,您可以调用此私有方法。

    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;
    }
    

    希望对你有所帮助。

    【讨论】:

    • 看来你没有理解我的问题manoj,让我详细说明一下。
    • 尝试添加另一个代码。您可以从您的第一个 API 调用此私有方法,将文件上传到其他 API。
    猜你喜欢
    • 2017-02-16
    • 1970-01-01
    • 2013-05-26
    • 2016-10-30
    • 1970-01-01
    • 1970-01-01
    • 2015-10-25
    • 2020-11-30
    • 1970-01-01
    相关资源
    最近更新 更多