C#web api成功状态的一般响应

时间:2016-12-15 12:17:22

标签: c#

如何在WEB API2中创建通用响应,而不是始终编写

return Ok(new { success = true });

所以我这样做,然后在角度检查中,如果reponse.success ===' true'

public IHttpActionResult Add(MyModel model)
        {
            if (ModelState.IsValid)
            {
                _helper.Create(model);
            }

            return Ok(new { success = true });
        }

2 个答案:

答案 0 :(得分:0)

这取决于您的需求。您想创建一个包含响应状态的泛型类吗?在这种情况下,您可以创建一个用于通用目的的类。

public class Response
{
    /// <summary>
    /// Gets or sets a value indicating whether this instance is success.
    /// </summary>
    /// <value>
    /// <c>true</c> if this instance is success; otherwise, <c>false</c>.
    /// </value>
    public bool IsSuccess { get; set; }

    /// <summary>
    /// Gets or sets the error message.
    /// </summary>
    /// <value>
    /// The error message.
    /// </value>
    public string ErrorMessage { get; set; }
}

之后你就可以这样使用:

 return Ok<Response>(new Response { ErrorMessage = "", IsSuccess = true });

或者您可以使用没有任何参数的Ok响应,并在角度应用上检查请求的状态代码:

return Ok();

角度部分:

    $http({
      method: 'GET',
      url: '/someUrl'
    })}).then(function successCallback(response) {
         //If it's Ok -> 200 HTTP
  }, function errorCallback(response) {
      //If error occured -> 500 HTTP etc.
  });

答案 1 :(得分:0)

当您从API返回Ok()时,实际发送的内容是HTTP Status Code 200。 Angular的AJAX函数使用它来确定是否调用successerror函数。有many other status codes that can be sent,但并非所有都有直接的Web API 2类来封装它们。

仅返回Ok()就足以告诉您的应用程序它已成功。如果在通话过程中可能发生多种情况,您将需要包含其他信息(您的对象)。例如,由于您的操作方法称为Add(),因此您可能想要返回的内容之一是您刚刚创建的对象的ID,但如果您不需要,则不要“必须。

你应该做的是不要在体内返回任何东西,如果你点击success角度函数,那么它就成功了。如果在通话期间发生了某些事情,则不会返回OK / 200响应,而是会调用error