gpt4 book ai didi

c# - 获取请求的 URL 或操作参数 i MediaTypeFormatter.ReadFromStreamAsync

转载 作者:太空狗 更新时间:2023-10-29 23:23:24 26 4
gpt4 key购买 nike

我有一个带有自定义 MediaTypeFormatter

的自托管 WebApi 应用程序

根据“名称”参数(或 URL 的一部分),应用程序应将请求正文格式化为不同的类型。

这是 Action

// http://localhost/api/fire/test/ 
// Route: "api/fire/{name}",

public HttpResponseMessage Post([FromUri] string name, object data)
{
// Snip
}

这是自定义的 MediaTypeFormatter.ReadFromStreamAsync

public override Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
{
var name = "test"; // TODO this should come from the current request

var formatter = _httpSelfHostConfiguration.Formatters.JsonFormatter;

if (name.Equals("test", StringComparison.InvariantCultureIgnoreCase))
{
return formatter.ReadFromStreamAsync(typeof(SomeType), readStream, content, formatterLogger);
}
else
{
return formatter.ReadFromStreamAsync(typeof(OtherType), readStream, content, formatterLogger);
}
}

最佳答案

这是您可以执行此操作的一种方法。让消息处理程序读取请求并添加这样的内容 header 。

public class TypeDecidingHandler : DelegatingHandler
{
protected override async Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request, CancellationToken cancellationToken)
{
// Inspect the request here and determine the type to be used
request.Content.Headers.Add("X-Type", "SomeType");

return await base.SendAsync(request, cancellationToken);
}
}

然后,您可以从 ReadFromStreamAsync 中的格式化程序读取此 header 。

public override Task<object> ReadFromStreamAsync(
Type type, Stream readStream,
HttpContent content,
IFormatterLogger formatterLogger)
{
string typeName = content.Headers.GetValues("X-Type").First();

// rest of the code based on typeName
}

关于c# - 获取请求的 URL 或操作参数 i MediaTypeFormatter.ReadFromStreamAsync,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17962778/

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