Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
63 views
in Technique[技术] by (71.8m points)

c# - convert ajax POST to .net with HttpClient

I have the following POST call in ajax and I would like to convert and implement the same call in .net Core 3.1.

this is the full code of which the ajax code is part of.

grecaptcha.ready(function() {
  grecaptcha.execute('ABCDEF', {
    action: 'homepage'
  }).then(function(token)

  ) {
    $.ajax({
      type: "POST",
      url: pathName + "/Login/SetToken/?captchaToken=" + token,
      contentType: "application/json; charset=utf-8",
      dataType: "json",
      success: function(response) {
        if (response == false) {
          document.getElementById("myCapcha").removeAttribute("class");
        }
      }
    });
  });
});

So I have tried implementing it, but always getting 400(BadRequest). That's what I have tried.

private static HttpClientHandler _clientHandler = new HttpClientHandler() { UseDefaultCredentials = true };
      
private async Task<bool> ValidateCaptcha(string googleToken)
{
    var result = new ResultOfOperation<object>();

    try
    {
        var response = new HttpResponseMessage();

        var client = new HttpClient(_clientHandler);
        client.DefaultRequestHeaders
            .Accept
            .Add(new MediaTypeWithQualityHeaderValue("application/json"));
            
        var captchaResponse = await client.PostAsJsonAsync(_googleCaptchaValidationUrl, googleToken);
        if (captchaResponse != null && captchaResponse.IsSuccessStatusCode)
        {
            var content = await captchaResponse.Content.ReadFromJsonAsync<bool>();
            result.IsSuccess = content;
        }
    }
    catch (Exception ex)
    {
        
    }

    return result.IsSuccess;   
}

Does my code look ok comparing to the ajax call?

question from:https://stackoverflow.com/questions/65617213/convert-ajax-post-to-net-with-httpclient

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...