0

I'm building a basic CRUD app in Blazor and upon adding an Event record (in AddEvent.razor) I want to redirect the user to the list of Events. The Post request goes through but the execution is not coming back and not hitting my NavigateTo to redirect to Event List page.

My Blazor solution is using WebAssembly hosting where I have:

  • A Client Project (.NET Standard 2.1)
  • Server Project REST API (dotnet core 3.1) using EntityFrameworkCore 3.1.8 and Microsoft.AspNetCore 3.2.1
  • Shared Project (.NET Standard 2.1)

This is how I configured my HttpClient in my Program.cs:

builder.Services.AddSingleton( new HttpClient
{
   BaseAddress = new Uri( builder.HostEnvironment.BaseAddress )
});

I have an AddEvent.razor page where I add an Event entity though the CreateEvent method:

    <div class="form-group">
        <button class="btn btn-primary" @onclick="@CreateEvent">Save</button>
        <button class="btn btn-warning" @onclick="@cancel">Cancel</button>
    </div>

Here is the CreateEvent definitionP

private async Task CreateEvent()
{
    try
    {
        //While debugging seems like UI thread is lost after this line, it doesn't reach the Navigation statement below
        var response = await Http.PostAsJsonAsync("/api/Event/create", evt);
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
    }

    await Task.Delay(500);
    Navigation.NavigateTo("/fetchevent");
}

My EventController class has this Post method:

// POST api/<controller>
[HttpPost("create")]
public ActionResult Post([FromBody]Event evt)
{
    if (ModelState.IsValid){
        _eventRepository.AddEvent(evt);
        return Ok();
    }
    return BadRequest();
}

My main problem is in the AddEvent.razor CreateEvent method where the execution seems to be lost after this line:

var response = await Http.PostAsJsonAsync("/api/Event/create", evt);

It never hits the navigation line below:

Navigation.NavigateTo("/fetchevent");

I have tried changing the signature of my EventController Post and wrapped the Http.PostAsJsonAsync call in a try/catch but it never hits the exception block. I also tried adding a delay after the Post but no luck...

This is what I see in the logs when I click on AddEvent button:

Microsoft.AspNetCore.Hosting.Diagnostics: Information: Request starting HTTP/1.1 POST http://localhost:54114/api/Event/create application/json; charset=utf-8 105
Microsoft.AspNetCore.Routing.EndpointMiddleware: Information: Executing endpoint 'Paycor.PartnerManager.Server.Controllers.EventController.Post (Paycor.PartnerManager.Server)'
Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker: Information: Route matched with {action = "Post", controller = "Event"}. Executing controller action with signature Microsoft.AspNetCore.Mvc.ActionResult Post(Paycor.PartnerManager.Shared.Models.Event) on controller Paycor.PartnerManager.Server.Controllers.EventController (Paycor.PartnerManager.Server).
Microsoft.AspNetCore.Hosting.Diagnostics: Information: Request starting HTTP/1.1 GET http://localhost:54114/addevent?  
Microsoft.AspNetCore.Routing.EndpointMiddleware: Information: Executing endpoint 'Fallback {*path:nonfile}'
Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware: Information: Sending file. Request path: '/index.html'. Physical path: 'C:\Development\GitRepos\Prototypes\Paycor.PartnerManager\PartnerManager\Client\wwwroot\index.html'
Microsoft.AspNetCore.Routing.EndpointMiddleware: Information: Executed endpoint 'Fallback {*path:nonfile}'
Microsoft.AspNetCore.Hosting.Diagnostics: Information: Request finished in 9.8383ms 200 text/html
Debugging hotkey: Shift+Alt+D (when application has focus)
Microsoft.AspNetCore.Hosting.Diagnostics: Information: Request starting HTTP/1.1 GET http://localhost:54114/_framework/blazor.boot.json  
Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware: Information: The file /_framework/blazor.boot.json was not modified
Microsoft.AspNetCore.Hosting.Diagnostics: Information: Request finished in 27.6226ms 304 application/json
Microsoft.AspNetCore.Mvc.StatusCodeResult: Information: Executing HttpStatusCodeResult, setting HTTP status code 200
Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker: Information: Executed action Paycor.PartnerManager.Server.Controllers.EventController.Post (Paycor.PartnerManager.Server) in 556.5854ms
Microsoft.AspNetCore.Routing.EndpointMiddleware: Information: Executed endpoint 'Paycor.PartnerManager.Server.Controllers.EventController.Post (Paycor.PartnerManager.Server)'
Microsoft.AspNetCore.Hosting.Diagnostics: Information: Request finished in 592.7471ms 0 

Any ideas of why PostAsJsonAsync call is not returning and continuing with the rest of the statements in my CreateEvent method?

Adolfo Perez
  • 2,834
  • 4
  • 41
  • 61
  • Have a look in the Browser Console... You are catching the exception w/o a re-throw. – H H Sep 20 '20 at 19:31
  • Are you hitting the controller? – Brian Parker Sep 20 '20 at 19:36
  • @BrianParker yes it hits the controller and adds my entity in the repo EF context but looks like the NavigateTo after the post in my AddEvent.razor doesn't get executed for some reason – Adolfo Perez Sep 20 '20 at 19:40
  • @HenkHolterman in browser console I see no error but looks like the page refreshes to the AddEvent page instead of navigating to the Event List – Adolfo Perez Sep 20 '20 at 19:52
  • Add a log statement for response.StatusCode and just before the NavigateTo(). Also check the basics, do you have a `@page "/fetchevent"` somewhere? – H H Sep 20 '20 at 19:54
  • I do have a page with "/fetchevent" Henk. I also added a log statement for Status code but it never shows which confirms what I suspected that it's not hitting that line – Adolfo Perez Sep 20 '20 at 19:59
  • Well, there is nothing obviously wrong with the code we can see. A simple mockup with the FetchData page fails to reproduce this. So it's in some part of the code you didn't post. Any other async stuff going on? A timer or something? – H H Sep 20 '20 at 20:41
  • Found a couple of links talking about enabling CORS, other about avoiding async/awaid deadlock by not doing await but doing .Result instead but nothing worked – Adolfo Perez Sep 20 '20 at 20:51
  • https://stackoverflow.com/questions/63002320/blazor-webassembly-api-call-children-could-not-be-evaluated https://stackoverflow.com/questions/30653770/httpclient-postasjsonasync-never-sees-when-the-post-is-succeeding-and-responding – Adolfo Perez Sep 20 '20 at 20:51
  • If it was CORS your API wouldn't be hit. `.Result` is always the wrong way. Look for `.Result` or `async void` in the rest of your code. – H H Sep 20 '20 at 22:42

0 Answers0