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

Lar*_*sen 5 c# self-hosting asp.net-web-api

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

根据"name"参数(或由此部分URL),应用程序应将请求主体格式化为不同的类型.

这是行动

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

public HttpResponseMessage Post([FromUri] string name, object data)
{
    // Snip
}
Run Code Online (Sandbox Code Playgroud)

这是自定义的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);
    }
}
Run Code Online (Sandbox Code Playgroud)

Bad*_*dri 3

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

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);
    }
} 
Run Code Online (Sandbox Code Playgroud)

然后,您可以从内部的格式化程序中读取此标头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
}
Run Code Online (Sandbox Code Playgroud)