0
votes

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.

2
Change your debug Console.WriteLine string to: response.Headers["TotalPages"].ToString() I think calling ToString on the list isn't going to give you what you are expecting - alec
thanks for response, but it always null, as following code response.Headers.GetValues("TotalPages").FirstOrDefault() generate Exception, because the Headers is null. - mRizvandi
Do you see the header in the browser network log ? - agua from mars
Why do you return a IList<Country> and the count in a header instead of a PaginatedResponse<Country> ? - agua from mars

2 Answers

2
votes

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!

0
votes

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