Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do i send a "forbidden" response in my Web API 2 solution?

I am making a web api to work with a legacy system. This web api should work in the same way as the old one. The security is to send a security token along with each call. This means that i need to check the token before serving data. I have a method like this:

public List<User> Get(string id, string securityToken)
        {
            //ValidateToken(securityToken);
            return userRepository.LoadAll();
        }

And in my method i would like the validateToken() method to return a "Forbidden" httpresponse if i cant validate it. How do i go around doing this?

like image 909
Brian Hvarregaard Avatar asked Nov 28 '22 07:11

Brian Hvarregaard


1 Answers

You can use an HttpResponseMessage like so:

public HttpResponseMessage Get(string id, string securityToken)
{
    var forbidden = true;
    if (forbidden)
    {
        return this.Request.CreateResponse(HttpStatusCode.Forbidden);
    }
    return Ok(userRepository.LoadAll());
}

Using HttpResponseMessage allows you to return OK (an HTTP 200) with content, or an error.

like image 78
vcsjones Avatar answered Dec 21 '22 23:12

vcsjones