简体   繁体   English

为什么我的Razor,ASP.NET,C#HTTPRequests不会返回响应的主体?

[英]Why won't my Razor, ASP.NET, C# HTTPRequests return the body of the Response?

My ultimate goal is to get reCaptcha to work in my Razor app, but I am stuck. 我的最终目标是让reCaptcha在我的Razor应用程序中运行,但我被卡住了。 I've gotten to the point where I can get Response Headers back, but have no idea how to get the actual JSON response body back. 我已经到了可以获得响应标头的地步,但不知道如何获得实际的JSON响应体。 Let me know if you need more info. 如果您需要更多信息,请告诉我。

In Startup.cs ---------------------------------- 在Startup.cs中----------------------------------

public void ConfigureServices(IServiceCollection services)
{
    services.AddHttpClient();

In Models > Voter.cs ---------------------------------- 在Models> Voter.cs中----------------------------------

using System.ComponentModel.DataAnnotations;

namespace rethianIdeas.Models
{
    public class Voter
    {
        [Required(ErrorMessage = "Data is required.")]
        public string reCaptchaPost { get; set; }

        public string Result { get; set; }
    }
}

In Vote2.cshtml.cs ---------------------------------- 在Vote2.cshtml.cs中----------------------------------

using System.Net.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using rethianIdeas.Models;
using System.ComponentModel.DataAnnotations;

namespace rethianIdeas.Pages.Ideas
{
    public class Vote2Model : PageModel
    {

        [BindProperty]
        public Voter reCaptchaTest { get; set; }

        [BindProperty(Name = "g-recaptcha-response")]
        [Required(ErrorMessage = "No One Beats Reacaptcha!")]
        public string reCaptchaG { get; set; }


        public IActionResult OnGet()
        {
            if (reCaptchaTest == null)
            {
                reCaptchaTest = new Voter();
            }

            return Page();
        }

        private readonly IHttpClientFactory _clientFactory;

        public Vote2Model(IHttpClientFactory clientFactory)
        {
            _clientFactory = clientFactory;
        }

        public IActionResult OnPost()
        {

            if (ModelState.IsValid)
            {
                string URL = "https://www.google.com/recaptcha/api/siteverify?secret=6LcUFJUUAAAAADvuNOTGONNAGETITiFgNNG0sxBg&response=";

                string Response_String = reCaptchaG;

                string GetRequest = URL + Response_String;

                var reCaptchaRequest = new HttpRequestMessage(HttpMethod.Get, GetRequest);
               reCaptchaRequest.Headers.Add("Accept", "application/json");


                var Client = _clientFactory.CreateClient().SendAsync(reCaptchaRequest);

                reCaptchaTest.Result = Client.Result.ToString();

            }

            return Page();
        }
    }
}

In Vote2.cshtml ---------------------------------- 在Vote2.cshtml中----------------------------------

@page
@model rethianIdeas.Pages.Ideas.Vote2Model

<script src="https://www.google.com/recaptcha/api.js" async defer></script>

<form method="post">
    <div asp-validation-summary="All"></div>
    <div>
        <div>
            <label asp-for="@Model.reCaptchaTest.reCaptchaPost"></label>
            <input asp-for="@Model.reCaptchaTest.reCaptchaPost" />
            <span asp-validation-for="@Model.reCaptchaTest.reCaptchaPost"></span>
        </div>
    </div>
    <div class="g-recaptcha" data-sitekey="6LcUFJUUAAAAANOTGETTINGIT0SYj77GZHEhz73p0Q6_m"></div>
    <div>
        <input type="submit" value="Submit">
    </div>
    <div><label>Result: @Model.reCaptchaTest.Result</label></div>
</form>

Returns ---------------------------------- 返回----------------------------------

Result: StatusCode: 200, ReasonPhrase: 'OK', Version: 1.1, Content: System.Net.Http.HttpConnection+HttpConnectionResponseContent, Headers: { Date: Fri, 08 Mar 2019 06:02:16 GMT Cache-Control: max-age=0, private X-Content-Type-Options: nosniff X-XSS-Protection: 1; mode=block Server: GSE Alt-Svc: quic=":443"; ma=2592000; v="46,44,43,39" Accept-Ranges: none Vary: Accept-Encoding Transfer-Encoding: chunked Content-Type: application/json; charset=utf-8 Expires: Fri, 08 Mar 2019 06:02:16 GMT }

I simply cannot figure out how to get the body of the request out of this thing. 我根本无法弄清楚如何从这个东西中获取请求的主体。 Please Help. 请帮忙。

You are calling an asynchronous method but not waiting ( await ) for it to return. 您正在调用异步方法但不等待( await )它返回。

This should get you going down the right path. 这应该让你走正确的道路。

public async Task<IActionResult> OnPost()
{
    if (ModelState.IsValid)
    {
        string URL = "https://www.google.com/recaptcha/api/siteverify?secret=***&response=";

        string Response_String = reCaptchaG;

        string GetRequest = URL + Response_String;

        var reCaptchaRequest = new HttpRequestMessage(HttpMethod.Get, GetRequest);
        reCaptchaRequest.Headers.Add("Accept", "application/json");

        var client = _clientFactory.CreateClient();

        var response = await client.SendAsync(reCaptchaRequest);

        if (response.IsSuccessStatusCode)
        {
            reCaptchaTest.Result = await response.Content.ReadAsStringAsync();
        }
        else
        {
            // Errors, do something...
        }
    }

    return Page();
}

You can reference the ASP.NET Core Http.Client docs for more info. 您可以参考ASP.NET Core Http.Client文档以获取更多信息。 Also, here is a blog post covering using ASP.NET Core and reCaptcha. 此外, 是一篇关于使用ASP.NET Core和reCaptcha的博客文章。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM