首页 > 解决方案 > HttpClient POST 与数据

问题描述

我有一个表单,用户将在其中插入数据并将其保存到数据库中。保存后,它将向给定的 URL(RequestURL) 发送数据。此 RequestURL 将分析数据并将结果传递回不同的 URL(ResponseURL)。下面是它的简单代码。

public class RequestSender
{
    private static HttpClient _client;

    public RequestSender()
    {
        if (_client== null)
        {
            _client= new HttpClient();
            _client.BaseAddress = new Uri("https://example.com/api/");
        }
    }

    [HttpPost]
    public async Task<string> SaveData()
    {
        // get data from the form
        // save the data
        // Save data is easy, already done it

        // Here is the problem
        // after save the data, it will send a post to the default URL
        var response = await _client.PostAsync(path);


        return "OK";
    }
}

我正在使用 httpclient,但问题是我只得到帖子的响应。我想要的是,它会像下面的表单中的操作属性一样发布数据并重定向到 URL。因此,URL 将处理数据并传回 ResponseURL。感谢你的帮助。

<form action="https://example.com/api/" method="post">

实际上我尝试集成支付网关。这是流程:

  1. 用户提交表单,保存到数据库。
  2. 表单保存成功后,将有另一个帖子从后端到 URL(支付站点)。
  3. 支付站点将处理发布数据并发送回 ResponseURL。
  4. 在这里,我将阅读响应并根据响应进行处理。

实际上,这可以通过从客户端提交另一个表单来完成,但我没有这样做,而是尝试在第一个表单中发布(保存数据)。

标签: c#asp.net-core.net-corehttpclient

解决方案


This part you have it already 1- User submit a form, save to the database.

2/3- After form save success, will have another post from the backend to the URL (Payment site). Payment site will be handling the post data and send back to the ResponseURL.

This can be done in 2 different ways, you do that using an HttpClient as @Alexander suggested

   var response = await _client.PostAsync(paymentUrl);
   var responseModel = JsonConvert.DeserializeObject<ResponseModelDto>(json)
   var returnUrl = responseModel.ReturnUrl

Or you need to do it from your front end, doing an async post to the PaymentPage and process the response (ResponseUrl) via javascript.

4 - Here I will read the response and handling it, based on the response. With the response, you can redirect you can do anything you need

 var returnUrl = responseModel.ReturnUrl;
 return Redirect(returnUrl);

But there are some integrations with payment websites, that you normally redirect the user passing parameters via a post or a get. The website handles the request as part of the querystring or as part of the body from your post, you should send as well a returnUrl, where they will send any information(Dto) back to be processed it from your side. But that will depend on your specific scenario. Hope this clarifies your doubts


推荐阅读