Simon
Simon

Reputation: 2035

Return json from web api controller

I have web api controller:

[HttpPost]
    public String UploadFile()
    {//do some logic
       String jsResult="{\"success\":\"false\", \"msg\":\"No file or user ID!\"}";
       return jsResult;
    }

Returned string to the client is like this: "{\"success\":\"false\", \"msg\":\"No file or user ID!\"}";

I compose json string manually but client doesn't parse it(I guess because returned string is escaped with "\". What would be the proper way to return json string to the clinet from this controller method?

Upvotes: 4

Views: 15978

Answers (2)

Mate
Mate

Reputation: 5274

Try auto serialize webapi:

Create a Model:

public class UploadResult
{
    public UploadResult()
    {

    }
    public bool Success  { get; set; }
    public string Msg { get; set; }
}

And return

public UploadResult UploadFile()
{
    var r = new UploadResult(){ Success = false, Msg = "No file or user ID!" };
    return r;
}

In your example, you are explicitly serializing, and the result ends up serialized twice. Because WebApi already has the Json serializer in the pipeline.

To go async:

public async Task<IHttpActionResult> UploadFile()
{
    var r = new UploadResult(){ Success = false, Msg = "No file or user ID!" };
    // some "await" logic
    return Ok(r);
}

Adding using System.Web.Mvc fails because

[System.Web.Http.HttpPost]  != [System.Web.Mvc.HttpPost]

And [HttpPost] is ambiguous. Anyway, the Mvc ref is not necessary . Remove it and add again [HttpPost]

Upvotes: 4

pete the pagan-gerbil
pete the pagan-gerbil

Reputation: 3166

Try this:

[HttpPost]
public JsonResult UploadFile()
{//do some logic
   String jsResult="{\"success\":\"false\", \"msg\":\"No file or user ID!\"}";
   return Json(jsResult);
}

I've changed the return type to JsonResult and used the Json method to format your result.

Upvotes: 0

Related Questions