我有一个带有自定义 MediaTypeFormatter
根据“名称”参数(或 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/