How can I pass parameter of type HttpContent in web api?

703 Views Asked by At

The back story is I have a web API that simply serves as a gateway to invoke external services. The reason for this is I don't want to expose the real business API to external services. So, in this gateway controller, it simply receives the information from the business API, calls external services and returns the response to the client, which is the business API.

In my gateway controller I have a POST action that takes a parameter of type HttpContent, something like this:

[Route("api/test")]
    public void Test(HttpContent content)
    {
    }

but the web API infrastructure doesn't know how to serialize and deserialize HttpContent type. Is there a way to support my scenario?

1

There are 1 best solutions below

2
On BEST ANSWER

Accessing the content of the request in any controller's handler is quite natural. Just call Request.Content inside. You can't have it as a parameter because it is not a mapping as an URI segment would nor a serialized content.

Try something like:

using System.Net;
using System.Net.Http;

//  namespace + controller definition...

[Route("api/test")]
public HttpResponseMessage GetTest() //  This is a GET handler
{
    var myRequestContext = Request.Content;

    //  Do something with the content e.g
    if (!myRequestContext.IsMimeMultipartContent())
    {
        Request.CreateResponse(HttpStatusCode.UnsupportedMediaType);
    }
}

BTW, assuming you are creating a REST API controller from what you said, don't forget to indicate the verb this handler is mapped to, either by using the [Http<REST_verb>] attribute in System.Web.Http on the handler or by prefixing the handler name by the verb.

Hope that helps!