Question

I have a self-hosted WebApi application with a custom MediaTypeFormatter

Depending on the "name" parameter (Or thereby part of the URL), the application should format the request body to varying types.

Here's the action

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

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

Here's the custom 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);
    }
}
Était-ce utile?

La solution

Here is one way you can do this. Have a message handler read the request and add a content header like this.

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

Then, you can read this header from the formatter inside 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
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top