简体   繁体   中英

C# web api generic response for success status

How to create generic response in WEB API2 instead always writing

return Ok(new { success = true });

So I am doing this and then in angular checking if reponse.success === 'true'

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

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

It depends on your needs. You want to create a generic class that contains your status of the response? In this case you can create a class for generic purpose.

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

And after that you can use like this:

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

Or you can use just the Ok response without any parameter and check the status code of the request on your angular app:

return Ok();

Angular part:

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

When you return Ok() from your API, what actually gets sent is an HTTP Status Code 200 . That is used by Angular's AJAX functions to determine whether to call your success or error functions. There are many other status codes that can be sent , however not all have direct Web API 2 classes to encapsulate them.

Returning only Ok() would be enough to tell your application that it succeeded. You will want to include other information (your object) if there are multiple things that could happen during the call. For example, since your action method is called Add() , one of the things you might want to return is the ID of the object you just created, but if you don't need to, you don't have to.

What you should do is to not return anything in the body, and if you hit your success Angular function, then it succeeded. If something happened during the call, an OK/200 response will not be returned, and your error will be called instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM