[英]Pass files to another asp.net core webapi from another webapi
現有的 ASP.NET 核心 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 core webapi 使用該 api,我必須僅通過 Request 對象傳遞這些文件,由於業務原因,我無法更改任何現有的 Api 代碼。
解決方案 1:如果您希望您的客戶端被重定向到其他 API,則適用
假設 API 調用者理解HTTP 302
並且可以采取相應的行動,那么302 redirect
應該對您有所幫助。
public IActionResult Post()
{
return Redirect("http://file-handler-api/action");
}
從文檔中,重定向方法向客戶端返回 302 或 301 響應。
解決方案 2:使用 HttpClient 發布文件的 C# 代碼
下面的 c# 代碼來自這篇博文。 這是創建 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;
}
希望這對你有幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.