4

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?

2 Answers 2

4

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]

10
  • I have ApiController: public class ImportReservationController : ApiController It doesn't have JsonResult option. If i add reference(using System.Web.Mvc;) then i can write JsonResult, but [HttpPost] doesn't work then. I guess API controller doesn't support JsonResult.
    – Simon
    Sep 3, 2015 at 7:53
  • It works now. Can you explain me in couple of words since i'm new to web api. And why if I add reference to MVC it stops working? [HttpPost] is not available any more. Thanks.
    – Simon
    Sep 3, 2015 at 8:10
  • Thanks. Other option would be to add like this: [System.Web.Mvc.HttpPost] And than I would be able to use JsonResult result?
    – Simon
    Sep 3, 2015 at 9:54
  • Hi, what if procedure returns result as table. What would be the best way to return table as json result?
    – Simon
    Sep 7, 2015 at 9:34
  • 1
    Thanks. It is everything clear now. i will open a new question.
    – Simon
    Sep 8, 2015 at 13:09
0

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.