Search code examples
c#asp.net-corerecaptchablazor-server-side

What is the .net5 replacement for 'await response.Content.ReadAsAsync<ReCAPTCHAVerificationResponse>()'


https://github.com/sample-by-jsakamoto/Blazor-UseGoogleReCAPTCHA is a sample implementation of reCaptcha V2 for Blazor. It contains a class named SampleApi which in turn contains the following line that fails to compile: var verificationResponse = await response.Content.ReadAsAsync<ReCAPTCHAVerificationResponse>();

Somewhere I found the suggestion to use: var verificationResponse = await JsonSerializer.DeserializeAsync<ReCAPTCHAVerificationResponse>(await response.Content.ReadAsStreamAsync()); but it did not work. It compiled but did not provide a usable verificationResponse.

I got it to work by installing Microsoft.AspNet.WebApi.Client, but it is deprecated. Seems like there must be a better way.


Solution

  • If you're using Newtonsoft.Json, you're looking for something like

    var content = await response.Content.ReadAsStreamAsync();
    var response = JsonConvert.DeserializeObject<ReCAPTCHAVerificationResponse>(content);
    

    If you're using System.Text.Json (Microsoft's flavor and recommended by them over Newtonsoft.Json for the most part)

    var response = response.Content.ReadAsAsync<ReCAPTCHAVerificationResponse>();
    

    However, this is not unique to Blazor nor .NET 5.