Blazor 服务器端应用程序 API 请求问题 httpClient.PostAsync IHttpClientFac



我正在开发一个 Blazor 服务器端应用程序。

api 调用会生成并下载 pdf 文件。

客户端没有显示任何错误,但我可以从服务器日志中看到未处理 API 调用。我能识别的唯一错误消息是状态代码:415,原因短语:不支持的媒体类型,版本:1.1,内容:System.Net.Http.Http.HttpConnectionResponseContent,标头。

获取异步工作正常 var response = await _httpClient.GetAsync($"xxx/yyyyy/zzzzz"(; 我现在遇到的唯一重要问题是使用新的 System.Text.Json.Serialization 进行序列化和反序列化,现在我已经通过开发自己的序列化和反序列化例程来解决这个问题,这些例程工作正常,我将使用它们,直到我解决了 System.Text.Json.Serialization 的问题。

我的问题与我无法开始工作的PostAsynch有关。我现在使用基本身份验证并发送 JSON 正文。我正在调用实时的 API,并且与其他调用它们的应用程序一起工作良好。他们在邮递员中也工作得很好,我只是无法让他们与 Blazor 合作。

//The relevant Startup code is as follows
services.AddHttpClient<Services.ApiServicerw>(client =>
{
client.BaseAddress = new Uri("https://www.xxxxxxxxxx.com");
});
//The code in the .razor page is as follows
@page "/runreport2"
@using BlazorApp1.Services
@inject ApiServicerw ApiService1
@using System.IO
<h1>Report</h1>
<p>This component demonstrates running a report</p>
@code {  
protected override async Task OnInitializedAsync()
{
var fresult = await ApiService1.GetContactsAsync(); 
}
}
//An extract of the code in the Services class is as follows
_httpClient.DefaultRequestHeaders.Authorization = new 
System.Net.Http.Headers.AuthenticationHeaderValue("Basic", encoded);
var stringContent = new StringContent(jsonString);
_httpClient.DefaultRequestHeaders.Accept.Add(new 
System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
var response = await _httpClient.PostAsync($"api/xxxx/yyyyyy",stringContent);

我已经解决了这个问题。我需要更改此行,如下所示

var stringContent = new StringContent(jsonString,System.Text.Encoding.UTF8, "application/json"(;

最新更新