更新时间:2023-02-15 22:20:08
嗯...我认为您不需要创建自定义格式化程序来完成这项工作.而是像这样返回内容:
Hmmm... I don't think you need to create a custom formatter to make this work. Instead return the content like this:
[HttpGet]
public HttpResponseMessage HelloWorld()
{
string result = "Hello world! Time is: " + DateTime.Now;
var resp = new HttpResponseMessage(HttpStatusCode.OK);
resp.Content = new StringContent(result, System.Text.Encoding.UTF8, "text/plain");
return resp;
}
这对我有用,无需使用自定义格式化程序.
This works for me without using a custom formatter.
如果您明确想要创建输出并覆盖基于 Accept 标头的默认内容协商,您将不想使用 Request.CreateResponse()
,因为它强制使用 mime 类型.
If you explicitly want to create output and override the default content negotiation based on Accept headers you won't want to use Request.CreateResponse()
because it forces the mime type.
而是显式创建一个新的 HttpResponseMessage
并手动分配内容.上面的示例使用 StringContent
,但还有很多其他内容类可用于从各种 .NET 数据类型/结构返回数据.
Instead explicitly create a new HttpResponseMessage
and assign the content manually. The example above uses StringContent
but there are quite a few other content classes available to return data from various .NET data types/structures.