24

I used this below code on my asp.net controller to return Json object on my Ajax on javascript

public JsonResult myMethod()
{
    // return a Json Object, you could define a new class
    return Json(new
    {
        Success = true, //error
        Message = "Success" //return exception
    });
}

Jquery-Ajax:

$.ajax({
    type: "POST",
    url: url_ ,
    data: search,
    success: function(data) {   
        //Show Json Properties from Controller ( If Success == false show exception Message from controller )
        if (data.Success)  
        {
            alert(data.Message); //display success 
        }
        else
        {
            alert(data.Message) //display exception
        }
    },
    error: function(XMLHttpRequest, textStatus, errorThrown) {
        alert("error: " + XMLHttpRequest.responseText);
    },
    dataType: 'json'
});

How can this be done on Web Api Controller?

Can you give me some examples or url as reference.

Thanks and Regards

3 Answers 3

30

ASP.NET Web API works with a little bit different philosophy. You should return just an entity (or set of entities) and it is up to content negotiation mechanism to return it to the client in the format which he has requested. You can read more about content negotiation here:

You can of course bypass the content negiotiation by returning a HttpResponseMessage. In this case yo need to serialize the object into JSON yourself (basics of this approach are also described in the article mentioned above).

Sign up to request clarification or add additional context in comments.

4 Comments

In my opinion, that is neither the philosophy of Web API or content negotiation. Returning arbitrary types is one particular style of using web API that is possible, but one that has a lot of potential pitfalls. Content negotiation is the mechanism where a client declares what media types it is able to process and the server attempts to accommodate the client's preferences. The emphasis is very different than saying the client is requesting format X. You can also still do conneg and return HttpResponseMessage.
@DarrelMiller In general I agree, and I wouldn't write this answer now as I did 4 months ago - good that yours is the accepted one. I believe some people found mine helpful mostly because of the content available under the link.
Hopefully more people will realize once they start using WebAPI that the initial appeal of just returning objects is not as useful as it appears.
In light of Web Api 2 and its IHttpActionResult, tpeczek answer appears to be the correct one.
26

If you create yourself a new HttpContent class for delivering JSON, like...

 public class JsonContent : HttpContent {

    private readonly MemoryStream _Stream = new MemoryStream();
    public JsonContent(object value) {

        Headers.ContentType = new MediaTypeHeaderValue("application/json");
        var jw = new JsonTextWriter( new StreamWriter(_Stream));
        jw.Formatting = Formatting.Indented;
        var serializer = new JsonSerializer();
        serializer.Serialize(jw, value);
        jw.Flush();
        _Stream.Position = 0;

    }
    protected override Task SerializeToStreamAsync(Stream stream, TransportContext context) {
        return _Stream.CopyToAsync(stream);
    }

    protected override bool TryComputeLength(out long length) {
        length = _Stream.Length;
        return true;
    }
}

Then you can do,

      public HttpResponseMessage Get() {
            return new HttpResponseMessage() {
                Content = new JsonContent(new
                {
                    Success = true, //error
                    Message = "Success" //return exception
                })
            };
        }

just like you do with JsonResult.

6 Comments

Why not use the default serialization behavior of the Web API and simply return your type directly and let the framework handle the serialization?
@TedNyberg Because sometimes it is very important to control your wire format. Letting a serializer make the decisions for you can make you dependent on that serializer and its configuration. This is less of an issue for Json than XML but it still can be an issue.
It might be good to include in this answer an example of how one would use the "default serialization behavior" (I myself am not entirely sure, is it Request.CreateResponse(....,myJsonObject)?)
@Assimilater That's one of a few ways. You can also just return a native CLR object from the controller method and a formatter will serialize it.
@DarrelMiller Ah, I see. From searching it seems that's another question in itself (been answered here)
|
10

After reading tpeczek's answer, Darrel Miller's answer, and their comment conversation in tpeczek's answer, I wanted get more guidance about when or why I might want to use Web Api and its content negotiation mechanism. tpeczek's link is informative and useful, but I found a couple other write-ups that were more geared at comparing the use of Web Api (and its content negotiation) with, say, plain MVC 4 controller actions that return JsonResult. Here are the ones that I found useful to making such a decision. One of the author concludes that he prefers using plain MVC 4 controllers while the other author prefers using Web Api controllers:

Building a Public HTTP API for Data

I believe there is one correction needed in the above author's post. In there he mentions that,

"...every [Controller] method that begins with 'Get' is automatically associated to the GET verb. Does it sound great? It is, but it also means that you can’t have two methods whose name begin with 'Get' in the same controller class."

According to this answer, you can indeed have multiple 'Get' methods in the same controller if you specify an ActionName attribute. Now here's the second post:

ASP.NET Web API vs. ASP.NET MVC “APIs”

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.