简体   繁体   中英

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM