5

我有一个自定义的自托管 WebApi 应用程序MediaTypeFormatter

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

这是动作

// 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);
    }
}
4

1 回答 1

4

这是您可以做到这一点的一种方法。让消息处理程序读取请求并添加这样的内容标头。

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

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
}
于 2013-07-31T06:52:08.627 回答