【问题标题】:HttpClient.GetAsync return HttpResponseMessage with null headerHttpClient.GetAsync 返回带有空头的 HttpResponseMessage
【发布时间】:2021-04-11 07:17:58
【问题描述】:

net 5.0 情人。

我是 blazor 和 .net 5.0 的新手,我使用 blazor WebAssembly 和 WebApi 开发应用程序。

有两个主要项目:客户端,服务器。

客户端是 Blazor WebAssembly,服务器是 WebApi 控制器项目。

在服务器端,在控制器中,HttpGet 方法,我向响应头添加一个值:

        [HttpGet]
    public async Task<ActionResult<IList<Country>>> GetAsync([FromQuery] Pagination paginationDto)
    {
        /...
        httpContext.Response.Headers.Add("TotalPages", totalPages.ToString());
        //...
        IList<Country> = ...
        return result;
    }

在客户端项目剃须刀页面中,使用以下方法从通用类调用api:

        protected virtual async Task<PaginatedResponse<O>> GetAsync<O>(Pagination pagination)
    {
        HttpResponseMessage response = null;

        try
        {
            response = await httpClient.GetAsync(RequestUri);

            if (response.IsSuccessStatusCode)
            {
                try
                {
                    //This response Header always is null!
                    System.Console.WriteLine("response.Headers: " + response.Headers.ToString());

                    O result = await response.Content.ReadFromJsonAsync<O>();

                    var paginatedResponse = new PaginatedResponse<O>
                    {
                        Response = result,
                        TotalPages = totalPages
                    };

                    return paginatedResponse;
                }
    //...
        return default;
    }

当从邮递员调用 Api 时,结果和 Header 都很好,并且 TotalPages 在那里。 在Client App中,结果是ok的,但是Header为null。

任何信息都会救我;-)

提前致谢。

【问题讨论】:

  • 将您的调试 Console.WriteLine 字符串更改为:response.Headers["TotalPages"].ToString() 我认为在列表中调用 ToString 不会给您所期望的结果
  • 感谢回复,但它始终为空,如下代码 response.Headers.GetValues("TotalPages").FirstOrDefault() 生成异常,因为 Headers 为空。
  • 你在浏览器网络日志中看到标题了吗?
  • 为什么你返回一个IList&lt;Country&gt; 和一个标题中的计数而不是一个PaginatedResponse&lt;Country&gt;

标签: asp.net-core blazor dotnet-httpclient webassembly response-headers


【解决方案1】:

这是如何搜索答案的确切答案:

在 Server 项目的 startup.cs 中的 ConfigureServices 方法中,为 CORS 添加以下代码或更新您的 CORS 规则:

                services.AddCors(options => options.AddPolicy(name: "WebApiProjectName or somthing", builder =>
        {
            builder.WithOrigins("http://localhost:xxxx") //xxxxx is server port
               .AllowAnyMethod()
               .AllowAnyHeader()
               //.AllowCredentials() // its optional for this answer
               .WithExposedHeaders("*"); // this is the code you need!
        }));

【讨论】:

    【解决方案2】:

    我认为您尝试使用标头传回可以更轻松地作为内容的一部分传递的结果,这使这变得过于复杂。您甚至有点意识到您正尝试在 Blazor 客户端中使用 PaginatedResponse

    因此,不是 API 只返回一个列表,而是在某个共享库中的某个地方有一个 PaginatedResponse 类。例如

        /// <summary>
        /// Paged result class
        /// </summary>
        /// <typeparam name="T"></typeparam>
        public class PaginatedResponse<T>
        {
    
            public int TotalPages { get; set; }
    
            public int Page { get; set; }
    
            public List<T> Data { get; set; }
    
        }
    

    然后你的 API 会返回这个

        [HttpGet]
        public async Task<ActionResult<PaginatedResponse<Country>>> GetAsync([FromQuery] Pagination paginationDto)
        {
            // ... query results here
            var result = new PaginatedResponse<Country>() 
            {
                 Page = x, 
                 TotalPages = totalPages,
                 Data = countrylist  // from query
            };
            return result;
        }
    

    然后,您的 Blazor 客户端可以使用相同的 PaginatedResponse,而只需使用标准的 GetFromJsonAsync 方法:

        var result = await Http.GetFromJsonAsync<PaginatedResponse<Country>>("yourApiUri");
    

    这就是我喜欢 Blazor 的原因!

    【讨论】:

    • 谢谢。它工作正常,我可以从 PaginationResponse 中获取 TotalPages,但我想知道,为什么不能从响应头中获取信息?或者为什么不能从代码访问标题,我的代码有什么错误?
    • @mRizvandi 我尝试使用.GetAsync 来查询 API,但我认为它无法正常工作,因此您不太可能修复它。如果你不顾一切地走那条路,我无能为力
    猜你喜欢
    • 1970-01-01
    • 2016-07-02
    • 1970-01-01
    • 2014-09-09
    • 2015-02-21
    • 2016-05-20
    • 1970-01-01
    • 2012-05-04
    • 2020-07-15
    相关资源
    最近更新 更多