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

时间:2013-07-31 06:04:50

标签: c# asp.net-web-api self-hosting

我有一个自定义的WebApi应用程序,其中包含自定义MediaTypeFormatter

根据“name”参数(或者因此是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);
    }
}

1 个答案:

答案 0 :(得分: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
}