Raelshark
Raelshark

Reputation: 3075

How to create an endpoint that accepts any content type in the request body using ASP.Net Web API

I'd like to create a generic API endpoint that a client can post text or file data to, where we won't know the content/media type of the data. It seems the framework requires a content formatter to be specified for any content-type passed in the HTTP header, or it throws an error. I don't want to have to define a formatter for every possible media type we might accept since we don't know yet what all they could include.

Is there a way to define an endpoint with a generic media type formatter, or not specify one at all? It doesn't seem to mind if I use a generic Object as my method parameter, but the framework keeps getting hung up on not being able to handle the media type without a formatter.

We don't actually need to be able to process this data, just store it (for something like a messaging system).

On a side note, I'd rather receive this data as the raw content of the request body and not use a multipart form request, but if it would make more sense to do it that way, it might be an option.

Upvotes: 0

Views: 645

Answers (2)

Darrel Miller
Darrel Miller

Reputation: 142222

Or if you want to go even more low level than Youssef's suggestion, you can do..

public Task<HttpResponseMessage> Post(HttpRequestMessage request) {

   var stream = await request.Content.ReadAsStreamAsync();

   return new HttpResponseMessage(HttpStatusCode.Ok) { RequestMessage = request } ;
}

Upvotes: 2

Youssef Moussaoui
Youssef Moussaoui

Reputation: 12395

You can bypass formatters entirely by reading the content yourself. Here's an example:

public async Task Post()
{
    string content = await Request.Content.ReadAsStringAsync();
    // Store away the content
}

This doesn't require you to use or define any formatters at all.

Upvotes: 2

Related Questions