Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does HttpResponseMessage return as Json

I have a basic question about basics on Web Api. FYI, I have checked before but could not found what I was looking for.

I have a piece of code as described below these lines. Just like any other Method in general terms my method called: Post, it has to return something,a JSON for example, How do I do that. Specifically, what am I supposed to write after the word " return " in order to get the 3 fields( loginRequest.Username,loginRequest.Password,loginRequest.ContractItemId ) as Json. Coments: Do not worry about username,password and contractID are in comments, I do get their value in my LinQ. It's just the return whta I nened now, greetings to all who would like to throw some notes about this.

    [System.Web.Http.HttpPost]
    public HttpResponseMessage Post(LoginModel loginRequest)
    {
        //loginRequest.Username = "staw_60";
        //loginRequest.Password = "john31";
        //loginRequest.ContractItemId = 2443;

      try
        {
           Membership member =
                (from m in db.Memberships
                 where
                     m.LoginID == loginRequest.Username 
                 && m.Password == loginRequest.Password 
                 && m.ContractItemID == loginRequest.ContractItemId
                 select m).SingleOrDefault();   
        }
       catch (Exception e)
       {
            throw new Exception(e.Message);
       }

      return ???;      
    }
like image 497
Mario Nic Avatar asked Jun 27 '13 17:06

Mario Nic


People also ask

What is return type of HttpResponseMessage?

A HttpResponseMessage allows us to work with the HTTP protocol (for example, with the headers property) and unifies our return type. In simple words an HttpResponseMessage is a way of returning a message/data from your action.

How do I return a JSON response in C#?

ContentType = "application/json; charset=utf-8"; Response. Write(json); Response. End(); To convert a C# object to JSON you can use a library such as Json.NET.


1 Answers

Try this:

HttpResponseMessage response = new HttpResponseMessage();
response.Content = new ObjectContent<Response>(
        new Response() { 
                        responseCode = Response.ResponseCodes.ItemNotFound 
                       }, 
                       new JsonMediaTypeFormatter(), "application/json");

or just create another response from Request object itself.

return Request.CreateResponse<Response>(HttpStatusCode.OK, 
      new Response() { responseCode = Response.ResponseCodes.ItemNotFound })

You can also turn all your response types to JSON by updating the HttpConfiguration(Formatter.Remove) just remove the default xml serialization and put JSON.

like image 102
vendettamit Avatar answered Oct 09 '22 16:10

vendettamit