Search code examples
asp.net-web-apiblazor-client-sideblazor-webassembly

Blazor project's httpClient does not send request to WebApi project


I created a custom solution containing a Blazor project, two class libraries and a WebApi project, I configured two different ports for blazor and api projects (since it is not possible to use one port), The api app url is: http://localhost:36855/, I copied a working blazor wasm (standard Microsoft template of 3 projects in a solution) files to these projects and I expected them to work, The Api project runs and I can test its action methods with postman, The Blazor project also runs but it can't send request to webapi projects, for example in the login page I have:

private async void HandleValidSubmit()
{        
    AjaxLoading = true;
    DisableLoginButton = true;
    ReturnModel = await genericService.PostModelAsyncOld<LoginModel>("api/Account/Login", Model);
    ...
}

The generic service is a class that httpclient is injected to it and its task is contacting with the server and Get and Post methods (it works in the project that I copied here):

public class GenericService : IGenericService
{
    private HttpClient httpClient;
    public GenericService(HttpClient httpClient)
    {
        this.httpClient = httpClient;
        //this.httpClient.BaseAddress = new Uri("http://localhost:36855/");
    }

    public async Task<AsyncReturn<TModel>> PostModelAsyncOld<TModel>(string uri, TModel model)
    {
        TModel returnModel = default(TModel);
        
        HttpResponseMessage result =
            await httpClient.PostAsync(uri, new StringContent(JsonConvert.SerializeObject(model), Encoding.UTF8, "application/json"));                                                     
        if (result.IsSuccessStatusCode)
        {                
            returnModel = JsonConvert.DeserializeObject<TModel>(result.Content.ReadAsStringAsync().Result);                ;                
            return new AsyncReturn<TModel>()
            { AsyncSuccess = true, Model = returnModel, StatusCode = System.Net.HttpStatusCode.OK };
        }
        else
        {                
            return new AsyncReturn<TModel>()
            { AsyncSuccess = false, Model = default(TModel), StatusCode = result.StatusCode };
        }

    }
 }

The api controller and action method (only works with PostMan not by HttpClient):

[ApiController]
[Route("api/[controller]")]   
public class AccountController : Controller
{
    .... 
    // inject services and other methods 
    ....

    [HttpPost]
    [Route("Login")]
    public async Task<LoginModel> Login(LoginModel model)    //, string returnUrl, string culture)
    {
        if (ModelState.IsValid) // **Breakpoint here, only hits with PostMan not by Blazor App**
        {
          ....

I also went to program.cs and made this change:

public class Program
{
    public static async Task Main(string[] args)
    {
        var builder = WebAssemblyHostBuilder.CreateDefault(args);
        builder.RootComponents.Add<App>("app");
        
        // The following line is the change:
        builder.Services.AddSingleton(sp => new HttpClient() { BaseAddress = new Uri("http://localhost:36855/") });           //builder.HostEnvironment.BaseAddress) });

        builder.Services              
          .AddHttpContextAccessor()
          .AddScoped<HttpContextAccessor>()
          .AddSingleton<ITokenService, TokenService>()
          .AddSingleton<IGenericService, GenericService>()
          .AddSingleton<ViewDataService>()              
          .AddBlazoredSessionStorage();

I did everything to make this work and it was not successful, What is the problem here?


Solution

  • After seeing Blazor error message through F12 I realized that CORS was causing this issue, So I added these lines of codes in ConfigureServices and Configure methods in startup file that solved the problem:

    services.AddCors();
    
    app.UseCors(x => x.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin());