【问题标题】:What does HttpResponseMessage return as JsonHttpResponseMessage 以 Json 形式返回什么
【发布时间】:2013-06-27 17:55:46
【问题描述】:

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

我有一段代码,如下所述。就像一般意义上的任何其他方法一样,我的方法称为:Post,它必须返回一些东西,例如 JSON,我该怎么做。 具体来说,为了将 3 个字段( loginRequest.Username、loginRequest.Password、loginRequest.ContractItemId )作为 Json,我应该在“return”这个词之后写什么。 评论:不用担心用户名、密码和合同 ID 在 cmets 中,我确实在我的 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 ???;      
    }

【问题讨论】:

  • OT: catch (Exception e) { throw new Exception(e.Message); } 是一个可怕的想法。祝你好运在没有合理的异常类型或堆栈跟踪的情况下跟踪任何错误!
  • @Adriano 这不是 MVC 这是Web-API 所以有点不同。
  • @RichardDeeming 我还要包括在这种情况下正确的错误处理是catch (Exception e) { throw; }。我会想象代码在那里用于断点调试,但仍然可以抛出断点并具有debuggablility
  • @ErikPhilips:我可以看出调试代码的意义,但在生产代码中我倾向于完全省略try...catch
  • @RichardDeeming 或至少实际做一些有用的事情,例如记录并发送回 HttpResponseMessage 和 500 或其他东西。

标签: c# json asp.net-web-api


【解决方案1】:

试试这个:

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

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

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

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

【讨论】:

  • 仅供参考:您可以使用 JsonMediaTypeFormatter.DefaultMediaType.MediaType 而不是硬编码媒体字符串。 ;)
  • 为什么这个方法会强制 Content Type?如果 API 的用户更喜欢请求 XML,而另一个用户更喜欢 JSON,该怎么办?最好返回请求指定的类型。
【解决方案2】:

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

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

如果你愿意,你可以直接从控制器返回:

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

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

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-02-03
    • 1970-01-01
    • 2020-06-29
    • 2017-03-10
    • 2016-10-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多