What does HttpResponseMessage return as Json

百般思念 提交于 2020-01-14 07:15:09

问题


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

回答1:


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.




回答2:


You could perhaps create a LoginResponseModel class that you can use to send back information to the caller about the success/failure of the login attempt. Something like:

public class LoginResponseModel
{
    public bool LoginSuccessful {get; set;}
    public string ErrorMessage {get; set;}
    public LoginResponseModel()
    {
    }
}

Then you can return this directly from the controller if you like:

[System.Web.Http.HttpPost]
public LoginResponseModel Post(LoginModel loginRequest)
{
    ...

    return new LoginResponseModel() { LoginSuccessful = true, ErrorMessage = "" };
}

Or you can still use a HttpResponseMessage as return type, but send a LoginResponseModel as the json response:

[System.Web.Http.HttpPost]
public HttpResponseMessage Post(LoginModel loginRequest)
{
    ...

    var resp = Request.CreateResponse<LoginResponseModel>(
        HttpStatusCode.OK,
        new LoginResponseModel() { LoginSuccessful = true, ErrorMessage = "" }
    );
    return resp;
}


来源:https://stackoverflow.com/questions/17350074/what-does-httpresponsemessage-return-as-json

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!