Search code examples
c#asp.net-web-apiasp.net-web-api2

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" http response if I can't validate it. How do I go around doing this?


Solution

  • Typically you'd do the ValidateToken type call in an ActionFilterAttribute, returning the forbidden at that time, long before the Get method was called on the controller. You'd then apply that attribute to the controller or action method (or register it as a global action filter attribute if you need to authorize ALL calls).