【问题标题】:Blazor server-side application api request issue httpClient.PostAsync IHttpClientFactoryBlazor 服务器端应用程序 api 请求问题 httpClient.PostAsync IHttpClientFactory
【发布时间】:2019-12-30 18:55:15
【问题描述】:

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

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

客户端没有显示错误,但我可以从服务器日志中看到 API 调用没有被处理。我能识别的唯一错误消息是 StatusCode: 415, ReasonPhrase: Unsupported Media Type, Version: 1.1, Content: System.Net.Http.HttpConnectionResponseContent, Headers。

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

我的问题与我无法开始工作的 PostAsynch 有关。我现在正在使用基本身份验证并发送 JSON 正文。我正在调用实时的 API,并且与调用它们的其他应用程序一起工作得很好。它们在 Postman 中也可以正常工作,但我无法让它们与 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);

【问题讨论】:

    标签: c# .net httpclient blazor blazor-server-side


    【解决方案1】:

    我已经解决了这个问题。我需要将这一行更改如下

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

    【讨论】:

      猜你喜欢
      • 2019-11-26
      • 2021-05-06
      • 2020-09-18
      • 2021-10-21
      • 2019-12-02
      • 1970-01-01
      • 2017-07-02
      • 1970-01-01
      • 2021-05-15
      相关资源
      最近更新 更多