C# HttpResponseMessage 作为 Json 返回什么

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17350074/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 09:15:39  来源:igfitidea点击:

What does HttpResponseMessage return as Json

c#jsonasp.net-web-api

提问by Mario Nic

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

我有一个关于 Web Api 基础知识的基本问题。仅供参考,我之前检查过,但找不到我要找的东西。

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.

我有一段代码,如下所述。就像任何其他方法一般来说,我的方法称为:Post,它必须返回一些东西,例如 JSON,我该怎么做。具体来说,为了将 3 个字段( loginRequest.Username,loginRequest.Password,loginRequest.ContractItemId )作为 Json,我应该在“return”这个词之后写什么。评论:不要担心用户名、密码和 contractID 在评论中,我确实在我的 LinQ 中得到了它们的价值。这只是我现在的回报,向所有想就此发表一些笔记的人致以问候。

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

回答by vendettamit

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.

或者只是从 Request 对象本身创建另一个响应。

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.

您还可以通过更新 HttpConfiguration(Formatter.Remove) 将所有响应类型转换为 JSON,只需删除默认的 xml 序列化并放入 JSON。

回答by user1429080

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

您也许可以创建一个LoginResponseModel类,您可以使用该类将有关登录尝试成功/失败的信息发送回调用者。就像是:

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 HttpResponseMessageas return type, but send a LoginResponseModelas the json response:

或者您仍然可以使用 aHttpResponseMessage作为返回类型,但发送 aLoginResponseModel作为 json 响应:

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

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