gpt4 book ai didi

asp.net-core - 将 POST 请求从 asp.net 核心 Controller 转发到不同的 URL

转载 作者:行者123 更新时间:2023-12-04 15:42:43 27 4
gpt4 key购买 nike

我想将传入的 POST 请求“按原样”(包括标题、正文、来自数据)转发到我的 asp.net 核心 Controller 到不同的 URL,而不使用中间件。

我找到了一个为 asp.net 执行此操作的示例:https://philsversion.com/2012/09/06/creating-a-proxy-with-apicontroller/

但这不适用于 asp.net 核心,因为调用
返回等待 http.SendAsync(this.Request);
在 asp.net 核心中接受一个 HttpRequestMessage 并且请求对象是 HttpRequest 类型。

我还发现了一些从 HttpRequest 创建 HttpRequestMessage 的代码,请参阅:Convert Microsoft.AspNetCore.Http.HttpRequest to HttpRequestMessage

使用此代码,接收端点(我转发到的端点)获取正文,但没有获取表单字段。

检查类 HttpRequestMessage 我看到它不包含 FormFields 的属性。

[Microsoft.AspNetCore.Mvc.HttpPost]
[NrgsRoute("api/redirect-v1/{key}")]
public async Task<HttpResponseMessage> Forward(
[FromUri] string key,
CancellationToken cancellationToken)
{
// the URL was shortened, we need to get the original URL to which we want to forward the POST request
var url = await _shortenUrlService.GetUrlFromToken(key, cancellationToken).ConfigureAwait(false);

using (var httpClient = new HttpClient())
{
var forwardUrl = new Uri(url);
Request.Path = new PathString(forwardUrl.PathAndQuery);

// see: https://stackoverflow.com/questions/45759417/convert-microsoft-aspnetcore-http-httprequest-to-httprequestmessage
var requestMessage = Request.ToHttpRequestMessage();
return await httpClient.SendAsync(requestMessage, cancellationToken);

// Problem: Forwards header and body but NOT form fields
}
}

预期的结果是在我的接收端点我有相同的
- 标题
- body
- 表单域
就像在原始 POST 请求中一样。

最佳答案

我最终做了以下事情:

[HttpPost]
[NrgsRoute("api/redirect-v1/{key}")]
public async Task<RedirectResult> Forward(string key, CancellationToken cancellationToken)
{
var url = await _shortenUrlService.GetUrlFromToken(key, cancellationToken).ConfigureAwait(false);
if (string.IsNullOrEmpty(url))
throw new BadRequestException($"Could not create forward URL from parameter {key}", "redirect-error");

using (var httpClient = new HttpClient())
{
var forwardUrl = new Uri(url);
Request.Path = new PathString(forwardUrl.PathAndQuery);

HttpResponseMessage responseMessage;
if (Request.HasFormContentType)
responseMessage = await ForwardFormData(key, httpClient, forwardUrl, cancellationToken);
else
responseMessage = await ForwardBody(key, httpClient, cancellationToken);

var queryParams = forwardUrl.GetQueryStringParams();
var lUlr = queryParams["lurl"];
return new RedirectResult(lUlr);
}
}

private async Task<HttpResponseMessage> ForwardFormData(string key, HttpClient httpClient, Uri forwardUrl, CancellationToken cancellationToken)
{
var formContent = new List<KeyValuePair<string, string>>();
HttpResponseMessage result;

if (Request.ContentType == "application/x-www-form-urlencoded")
{
foreach (var formKey in Request.Form.Keys)
{
var content = Request.Form[formKey].FirstOrDefault();
if (content != null)
formContent.Add(new KeyValuePair<string, string>(formKey, content));
}
var formUrlEncodedContent = new FormUrlEncodedContent(formContent);
result = await httpClient.PostAsync(forwardUrl, formUrlEncodedContent, cancellationToken);
}
else
{
var multipartFormDataContent = new MultipartFormDataContent();
foreach (var formKey in Request.Form.Keys)
{
var content = Request.Form[formKey].FirstOrDefault();
if (content != null)
multipartFormDataContent.Add(new StringContent(content), formKey);
}

result = await httpClient.PostAsync(forwardUrl, multipartFormDataContent, cancellationToken);
}

return result;
}

private async Task<HttpResponseMessage> ForwardBody(string key, HttpClient httpClient, CancellationToken cancellationToken)
{
// we do not have direct access to Content, see: https://stackoverflow.com/questions/41508664/net-core-forward-a-local-api-form-data-post-request-to-remote-api

var requestMessage = Request.ToHttpRequestMessage();
return await httpClient.SendAsync(requestMessage, cancellationToken);
}

关于asp.net-core - 将 POST 请求从 asp.net 核心 Controller 转发到不同的 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57214931/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com