Search code examples
.netblazor-webassembly.net-8.0

.NET 8 Blazor Web App API call returning status code 0


I am using the new .NET 8 Blazor Web Application template that creates a server and a client project within the solution allowing server side rendering, WASM, and AUTO. I also have an entirely separate API solution that this application is meant to call that retrieves data from a database. In the client side I have a service that consumes a HttpClient defined in the client side program.cs file. When triggering an API call I can watch through debug on the client that the service conducts the API call and I can see while debugging on the API itself that it is receiving the call, querying the data and returning X number of rows of data to the client. Yet in the client it self it is saying that the call is returning null. I have spent too much time trying to figure this out, why is the client receiving null when the API is returning data?

Service:

namespace Dispatch.Client.Services
{
    public class DispatchAPI : IDispatchAPI
    {
        private readonly HttpClient httpClient;

        public DispatchAPI(HttpClient httpClient)
        {
            this.httpClient = httpClient;
        }
        public async Task<List<ProductionMinutesByDay>> GetProductionMinutesSeriesAsync(string department, DateTime? startDate, DateTime? endDate)
        {
            try
            {                    
                var request = new HttpRequestMessage(HttpMethod.Get, $"/ProdMinutes/ProdMinutes?department={department}&startDate={startDate}&enddate={endDate}");
                request.SetBrowserRequestMode(BrowserRequestMode.NoCors);
                var response = await httpClient.SendAsync(request);
                if (response.IsSuccessStatusCode)
                {
                    var prodMinStr = response.Content.ReadAsStream();
                    var prodMin = JsonSerializer.Deserialize<List<ProductionMinutesByDay>>(prodMinStr);
                    return prodMin;
                }
                throw new Exception(response.StatusCode.ToString());


            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.ToString);
                return null;
            }

        }
    }
}

Program.css

var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.Services.AddSyncfusionBlazor();
builder.Services.AddSingleton<IDispatchAPI, DispatchAPI>();
builder.Services.AddHttpClient<IDispatchAPI, DispatchAPI>(client =>
{
    client.BaseAddress = new Uri("https://localhost:7239");
});

await builder.Build().RunAsync();

API Controller

namespace DispatchAPI.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class ProdMinutesController: ControllerBase
    {
        private readonly IProdMinutesRepository _repository;
        private readonly IConfiguration _configuration;

        public ProdMinutesController(IProdMinutesRepository repository, IConfiguration configuration)
        {
            _repository = repository;
            _configuration = configuration;
        }

        [HttpGet("ProdMinutes")]
        public async Task<List<ProdMinutesDayDTO>> ProdMinutes(string? department, DateTime startDate, DateTime enddate)
        {
            var prodMinSeries = await _repository.GetProdMinutesSeriesAsync(JdeUtility.PadDepartment(department), JdeUtility.ConvertDateToJulian(startDate), JdeUtility.ConvertDateToJulian(enddate));
            return prodMinSeries;
        }
    }
}

Client Calling API: enter image description here

API returning data: enter image description here

Client Service receiving null: enter image description here

Dev Tools NetWork Request: enter image description here

Preview of Net Work Request: enter image description here


Solution

  • According to your info, you are sending a request to a different origin, that's why you receive CORS error and .NET WASM cannot receive the Status code. You tried to set request mode to no-cors but that means no code can read the response:

    Prevents the method from being anything other than HEAD, GET or POST, and the headers from being anything other than CORS-safelisted request headers. If any ServiceWorkers intercept these requests, they may not add or override any headers except for those that are CORS-safelisted request headers. In addition, JavaScript may not access any properties of the resulting Response. This ensures that ServiceWorkers do not affect the semantics of the Web and prevents security and privacy issues arising from leaking data across domains.

    You have to properly add CORS support to your Web API. See Enable Cross-Origin Requests (CORS) in ASP.NET Core