mRizvandi
mRizvandi

Reputation: 1093

HttpClient.GetAsync return HttpResponseMessage with null header

net 5.0 lover.

I am new in blazor and .net 5.0, I develop the application with blazor WebAssembly and WebApi.

There are two major Projects: Client, Server.

Client is Blazor WebAssembly and Server is WebApi Controller Project.

In server side, in controller, HttpGet Method, i add a value to Response header:

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

In Client project razor page, call the api with following method from generic calss:

        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;
    }

When Api call from postman the result and Header is fine and TotalPages is there. In Client App, the result is ok, but the Header is null.

Any information will save me ;-)

Thanks in Advance.

Upvotes: 0

Views: 1841

Answers (2)

mRizvandi
mRizvandi

Reputation: 1093

This is the exactly answer for how search for answer:

in Server project, in startup.cs, in ConfigureServices method, add following code for CORS or update your CORS rule:

                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!
        }));

Upvotes: 2

Quango
Quango

Reputation: 13458

I think you're overcomplicating this by trying to use headers to pass back a result that can be passed more easily as part of the content. You even sort of realise this you're trying to use a PaginatedResponse in the Blazor client.

So instead of the API returning just a list, have a PaginatedResponse class in a shared library somewhere.. e.g.

    /// <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; }

    }

Your API then returns this

    [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;
    }

Your Blazor client can then use the same PaginatedResponse class and just use the standard GetFromJsonAsync method:

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

This is why I love Blazor!

Upvotes: 2

Related Questions