Вы можете использовать HttpClient
, чтобы получить файл, который возвращается из API, я создал простую демонстрацию для вашей справки.
Во-первых, чтобы создать файл слова, вам нужно скачать DocumentFormat.OpenXml
DLL в ваш проект API.
API:
[Route("api/[controller]")]
[ApiController]
public class GetDocumentByIdController : ControllerBase
{
[HttpGet("{id}")]
public IActionResult GenerateDocx(int id)
{
using (MemoryStream mem = new MemoryStream())
{
using (WordprocessingDocument wordDocument =
WordprocessingDocument.Create(mem, WordprocessingDocumentType.Document))
{
// Add a main document part.
MainDocumentPart mainPart = wordDocument.AddMainDocumentPart();
// Create the document structure and add some text.
mainPart.Document = new Document();
Body body = mainPart.Document.AppendChild(new Body());
Paragraph para = body.AppendChild(new Paragraph());
Run run = para.AppendChild(new Run());
run.AppendChild(new Text("The text in docx which created by " + id.ToString()));
}
return File(mem.ToArray(), "application/vnd.openxmlformats-officedocument.wordprocessingml.document");
}
}
}
Консольное приложение:
class Program
{
static void Main(string[] args)
{
try
{
UriBuilder builder = new UriBuilder("http://localhost:50855/api/ApiCode/GenerateDocx/1");
builder.Query = "id=1";// you can pass any other value
HttpClient client = new HttpClient();
var contentBytes = client.GetByteArrayAsync(builder.Uri).Result;
MemoryStream stream = new MemoryStream(contentBytes);
FileStream file = new FileStream(@"C:\Temp\ABC.docx", FileMode.Create, FileAccess.Write);
stream.WriteTo(file);
file.Close();
stream.Close();
}
catch (Exception)
{
throw; //throws 'TypeError: Failed to fetch'
}
}
}
После запуска консольного приложения вы найдете a word file named ABC
на пути C:. \ Temp