gpt4 book ai didi

asp.net-mvc - 在 MVC 6 中将 HTTP 响应传递给客户端

转载 作者:行者123 更新时间:2023-12-05 03:12:57 26 4
gpt4 key购买 nike

我是 Web API 和 HTTP 的新手。

我正在使用 MVC 6(测试版)。我有一个代理服务(Web API),它有一个 POST 方法来从另一个返回 XML 内容的服务获取响应。客户端不能直接调用服务,需要返回响应内容给客户端。

// In my proxy service
public HttpResponseMessage Post(String content)
{
using ( HttpClient client = new HttpClient() ) {

.......

HttpResponseMessage response = client.PostAsync(uri, content).Result;

// I get everything I need in the "response".

// How to return the response or it body to the client.
// return response;
}
}

我需要将“响应”返回给客户端,无需更改或更改最少。我试过“返回响应”,或创建一个新的 HttpResponseMessage,但我只得到类似的东西

{"Headers":[{"Key":"Content-Type","Value":["text/xml"]}]} 

在体内。

那么有没有一种简单的方法可以将响应传回给客户端呢?谢谢。

最佳答案

ASP.NET 团队目前正在开发一种“代理中间件”,它可以满足您的需求:https://github.com/aspnet/Proxy

这是它在内部的工作方式:

public async Task Invoke(HttpContext context)
{
var requestMessage = new HttpRequestMessage();
if (string.Equals(context.Request.Method, "POST", StringComparison.OrdinalIgnoreCase))
{
var streamContent = new StreamContent(context.Request.Body);
requestMessage.Content = streamContent;
}

// Copy the request headers
foreach (var header in context.Request.Headers)
{
if (!requestMessage.Headers.TryAddWithoutValidation(header.Key, header.Value) && requestMessage.Content != null)
{
requestMessage.Content?.Headers.TryAddWithoutValidation(header.Key, header.Value);
}
}

requestMessage.Headers.Host = _options.Host + ":" + _options.Port;
var uriString = $"{_options.Scheme}://{_options.Host}:{_options.Port}{context.Request.PathBase}{context.Request.Path}{context.Request.QueryString}";
requestMessage.RequestUri = new Uri(uriString);
requestMessage.Method = new HttpMethod(context.Request.Method);
using (var responseMessage = await _httpClient.SendAsync(requestMessage, HttpCompletionOption.ResponseHeadersRead, context.RequestAborted))
{
context.Response.StatusCode = (int)responseMessage.StatusCode;
foreach (var header in responseMessage.Headers)
{
context.Response.Headers.SetValues(header.Key, header.Value.ToArray());
}

foreach (var header in responseMessage.Content.Headers)
{
context.Response.Headers.SetValues(header.Key, header.Value.ToArray());
}

// SendAsync removes chunking from the response. This removes the header so it doesn't expect a chunked response.
context.Response.Headers.Remove("transfer-encoding");
await responseMessage.Content.CopyToAsync(context.Response.Body);
}
}

https://github.com/aspnet/Proxy/blob/dev/src/Microsoft.AspNet.Proxy/ProxyMiddleware.cs

关于asp.net-mvc - 在 MVC 6 中将 HTTP 响应传递给客户端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31925621/

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