10

如何输出 Request.CreateResponse 方法的 json 对象?

下面的代码输出json字符串

    "{RowCount:15}"

,字符串不是json ojbect,它应该使用javscript的eval()方法转换为json对象,我希望服务器端直接返回json对象,它应该返回

{RowCount:15}

那是一个json对象。

代码

public class PagedDataAttribute : ActionFilterAttribute
{

    public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
    {
        string jsonRowCount = "{RowCount:10}";
        actionExecutedContext.Response = actionExecutedContext.Request.CreateResponse(System.Net.HttpStatusCode.OK, jsonRowCount,System.Net.Http.Formatting.JsonMediaTypeFormatter.DefaultMediaType);
    }

}
4

1 回答 1

25

Instead of using a string, use an anonymous object:

public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
{
    var rowCount = new { RowCount = 10 };
    actionExecutedContext.Response = actionExecutedContext.Request.CreateResponse(
        HttpStatusCode.OK,
        rowCount,
        JsonMediaTypeFormatter.DefaultMediaType
    );
}
于 2013-05-10T07:12:41.967 回答