Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to output a json object of Request.CreateResponse method

How to output a json object of Request.CreateResponse method?

the below code output the json string

    "{RowCount:15}"

,the string is not a json ojbect,it should use eval() method of javscript to convert to json object ,I want the server side return the json object directly, It should return

{RowCount:15}

that's a json object.

Code

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);
    }

}
like image 957
sam Avatar asked May 10 '13 07:05

sam


1 Answers

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
    );
}
like image 125
Darin Dimitrov Avatar answered Nov 14 '22 03:11

Darin Dimitrov