2013-07-31 9 views
5

Ho un'applicazione WebAPI self-hosted con un costume MediaTypeFormatterGet URL richiesto o un parametro di azione i MediaTypeFormatter.ReadFromStreamAsync

A seconda del parametro "nome" (o in tal modo parte dell'URL), l'applicazione deve formattare il corpo della richiesta a vari tipi.

Ecco l'azione

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

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

Ecco l'usanza 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); 
    } 
} 

risposta

4

Ecco un modo si può fare questo. Chiedere a un gestore di messaggi di leggere la richiesta e aggiungere un'intestazione di contenuto come questa.

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

Quindi, è possibile leggere questo colpo di testa da dentro formattatore 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 
} 
+0

grazie è stata una buona soluzione –