简体   繁体   中英

REST api responses

Given this code, the entry for a C# REST API,

protected HttpResponseMessage ProcessRequest()
{
    HttpResponseMessage _response = null;
    try
    {
        //request is processed.
        object _obj = ExecuteEvent();

        //response object is created with success status and response content is assigned in the required mediatype format.
        _response = Request.CreateResponse(HttpStatusCode.OK, Constants.ServiceConstants.VALUE);
        _response.Content = new StringContent(System.Web.Helpers.Json.Encode(_obj), Encoding.UTF8, Constants.ServiceConstants.MEDIATYPE);
    }
    catch
    {
    }
    return _response;
}

Returning a 200 response for every request and just setting the content to the serialized JSON as above, is this the right or wrong way to go about this?

I would have thought that we definitely should not just be returning a 200 OK for every request.

This code will throw an exception in ExecuteEvent , let's say if the user is unauthorized, however, shouldn't we actually be telling the caller that their request is unauthorized?

You should send back an HTTP status based ok what happened in your method. If everything worked correctly, you send back an OK. If there is a failure, you should send back the appropriate status code.

For example, if ExecuteEvent throws a message indicating that the user is not authorized, you would send back an HTTP stays code of Forbidden (a 403).

You can see all of Microsft's status codes here and you can get a list of the numbers and what they mean here . Most of the time these two lists with correspond to each other, they are just organized a little differently.

Hope that helps.

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