c# - 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">
实际上我尝试集成支付网关。这是流程:
- 用户提交表单,保存到数据库。
- 表单保存成功后,将有另一个帖子从后端到 URL(支付站点)。
- 支付站点将处理发布数据并发送回 ResponseURL。
- 在这里,我将阅读响应并根据响应进行处理。
实际上,这可以通过从客户端提交另一个表单来完成,但我没有这样做,而是尝试在第一个表单中发布(保存数据)。
解决方案
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
推荐阅读
- r - 如何从 R 中的 URL 路径中提取文本?
- java - 在 Eclipse SWT 指针中覆盖 performSave()/doSave() 方法
- node.js - 如何将多个数据类型分配给mongodb中的变量?
- java - 动画矢量可绘制动画无法正常工作
- azure - 如何帮助 LUIS 检测“半英里”、“四分之一磅”等
- c# - 访问路径'/proc/1/map_files'被拒绝.NET Core 2.1 Centos 7
- frameworks - 示例 Appium 框架
- d3.js - D3 图表集成到 Vuejs
- c# - 使用带有字符串拆分的 linq
- mysql - 在单个 UPDATE 请求中更新多条记录