[英]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. 我想创建一个通用的API端点,客户端可以将文本或文件数据发布到该端点,而我们不知道数据的内容/媒体类型。 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.
似乎该框架要求为HTTP头中传递的任何内容类型指定一个内容格式化程序,否则会引发错误。 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.. 或者,如果您想比Youssef的建议低得多,也可以做。
public Task<HttpResponseMessage> Post(HttpRequestMessage request) {
var stream = await request.Content.ReadAsStreamAsync();
return new HttpResponseMessage(HttpStatusCode.Ok) { RequestMessage = request } ;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.