有几种选择。最简单的方法是让您的方法返回 a HttpResponseMessage
,并根据您的字符串使用 a 创建响应StringContent
,类似于下面的代码:
public HttpResponseMessage Get()
{
string yourJson = GetJsonFromSomewhere();
var response = this.Request.CreateResponse(HttpStatusCode.OK);
response.Content = new StringContent(yourJson, Encoding.UTF8, "application/json");
return response;
}
并检查 null 或空 JSON 字符串
public HttpResponseMessage Get()
{
string yourJson = GetJsonFromSomewhere();
if (!string.IsNullOrEmpty(yourJson))
{
var response = this.Request.CreateResponse(HttpStatusCode.OK);
response.Content = new StringContent(yourJson, Encoding.UTF8, "application/json");
return response;
}
throw new HttpResponseException(HttpStatusCode.NotFound);
}