有几种选择。最简单的方法是让您的方法返回HttpResponseMessage
,并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);
}