dotnet / aspnetcore

ASP.NET Core is a cross-platform .NET framework for building modern cloud-based web applications on Windows, Mac, or Linux.
https://asp.net
MIT License
35.21k stars 9.95k forks source link

httpClient.PostJsonAsync returns an exception in ASP.NET 3.0 #13052

Closed Harardin closed 4 years ago

Harardin commented 5 years ago

Thing is the issue can be handled by simple try and catch but as I read they are expensive for performance if used too much, so I prefer to handle all troubles manually if it is possible.

So to the code sample:

The Controller Class:

[HttpPost]
        public async Task<IActionResult> AsyncRegistration([FromBody]RegistrationForm registrationForm)
        {
            if(context.UsersData.Any(o => o.UserEmail == registrationForm.Email))
            {
                // User already exists
                return StatusCode(302);
            }
            Users users = new Users() {
                UserEmail = registrationForm.Email,
                UserPassword = registrationForm.Password,
                UserRegDate = DateTime.Now,
                UserName = registrationForm.UserName,
                UserRole = "user"
            };
            await context.UsersData.AddAsync(users);
            await context.SaveChangesAsync();

            return Ok();
        }

Nothing special in it

And the blazor page code:

@code
{
    private RegistrationForm registrationForm = new RegistrationForm();

    private async Task RegistrationAsync()
    {
        // Throws an exception about the HttpResponse if not Success 200OK
        var responce = await httpClient.PostJsonAsync<HttpResponseMessage>("https://localhost:44389/api/Registration", registrationForm);

        // Code is not accessible because of the exception and just stops on the line of PostJsonAsync

        // Returns an actual Status code if the user is registered and etc.
        string JsonData = JsonConvert.SerializeObject(registrationForm);
        StringContent content = new StringContent(JsonData, Encoding.UTF8, "application/json");
        httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

        var responce = await httpClient.PostAsync("https://localhost:44389/api/Registration", content);

        // Code is accessible in this scenario
    }
}

If I miss something and made a mistake somewhere please let me know and I close this issue as false alarmed.

mkArtakMSFT commented 5 years ago

Thanks for contacting us, @Harardin. What's the exception you're getting? Please share a small repro project, so we can investigate this.

Harardin commented 5 years ago

Thanks for contacting us, @Harardin. What's the exception you're getting? Please share a small repro project, so we can investigate this.

Here is the exception from the log which comes from this line of code var responce = await httpClient.PostJsonAsync<HttpResponseMessage>("https://localhost:44389/api/Registration", registrationForm); :

System.Net.Http.HttpRequestException: Response status code does not indicate success: 302 (Found).
   at System.Net.Http.HttpResponseMessage.EnsureSuccessStatusCode()
   at Microsoft.AspNetCore.Components.HttpClientJsonExtensions.SendJsonAsync[T](HttpClient httpClient, HttpMethod method, String requestUri, Object content)
   at CMS_Blazor.Pages.Dialogs.LoginDialog.RegistrationSentence.RegistrationAsync() in E:\SharpProjects\ASPProgects\CMS-Blazor\CMS-Blazor\Pages\Dialogs\LoginDialog\RegistrationSentence.razor:line 40
   at Microsoft.AspNetCore.Components.ComponentBase.CallStateHasChangedOnAsyncCompletion(Task task)
   at Microsoft.AspNetCore.Components.Forms.EditForm.HandleSubmitAsync()
   at Microsoft.AspNetCore.Components.ComponentBase.CallStateHasChangedOnAsyncCompletion(Task task)
   at Microsoft.AspNetCore.Components.Rendering.Renderer.GetErrorHandledTask(Task taskToHandle)
Microsoft.AspNetCore.Components.Server.ComponentHub: Warning: Unhandled Server-Side exception

System.Net.Http.HttpRequestException: Response status code does not indicate success: 302 (Found).
   at System.Net.Http.HttpResponseMessage.EnsureSuccessStatusCode()
   at Microsoft.AspNetCore.Components.HttpClientJsonExtensions.SendJsonAsync[T](HttpClient httpClient, HttpMethod method, String requestUri, Object content)
   at CMS_Blazor.Pages.Dialogs.LoginDialog.RegistrationSentence.RegistrationAsync() in E:\SharpProjects\ASPProgects\CMS-Blazor\CMS-Blazor\Pages\Dialogs\LoginDialog\RegistrationSentence.razor:line 40
   at Microsoft.AspNetCore.Components.ComponentBase.CallStateHasChangedOnAsyncCompletion(Task task)
   at Microsoft.AspNetCore.Components.Forms.EditForm.HandleSubmitAsync()
   at Microsoft.AspNetCore.Components.ComponentBase.CallStateHasChangedOnAsyncCompletion(Task task)
   at Microsoft.AspNetCore.Components.Rendering.Renderer.GetErrorHandledTask(Task taskToHandle)

And a link on the project: project This is my small out of the main job project, I want to create a small CMS with ASP.NET and Blazor.

You need to look at Controllers folder there is a Registration Controller that takes a User data here is the link to a cs file: RegistrationController

And the Blazor page that makes a request link: Registration-Blazor-Page

StephenHoust commented 4 years ago

I am having the exact same issue with a client-side Blazor app with an ASP.Net Core host. I'm using .Net Core 3.0 release version (client-side packages still preview 9.19465.2 of course).

mkArtakMSFT commented 4 years ago

Thanks for contacting us. This is going to be covered as part of a separate package for the final Blazor WASM release. There is no pending work for us here.