Executing code when accessing API controllers

I have the following code:

CookieHeaderValue cookie = Request.Headers.GetCookies("session").FirstOrDefault();
var isAuthenticated = _userService.IsAuthenticated(cookie);

if (!isAuthenticated) 
    return Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "");

I'd like this code to execute as soon as any part of my api is called. I havn't found any good solutions or ways to do this so i thought i would ask here instead.

(what I do now is execute the code in every get/post/put/delete which is horrible).


The best place to solve this would be an authorization filter attribute. See Authentication Filters in ASP.NET Web API 2.

The subject is too broad to repeat here in its entirety, but it comes down to creating an attribute:

public class CookieAuthenticationFilterAttribute : Attribute, IAuthenticationFilter
    public async Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken)
        // your cookie code

And applying it to the controller or action methods:


But be sure to read the link.

You can use an ActionFilter or AuthorizationFilter for this purpose. These are attribute classes that you can use on specific controllers/actions or globally. So you don't need to repeat the code for every action.

See this link for details. It shows the general authentication/authorization flow in ASP.NET Web API and how you can customize it.

So i found the best solution for my problem was the following code:

public class CookieFilterAttribute : AuthorizeAttribute
    public IUserService UserService { get; set; }

    protected override bool IsAuthorized(HttpActionContext actionContext)
        CookieHeaderValue cookie = actionContext.Request.Headers.GetCookies("session").FirstOrDefault();
        var isAuthenticated = UserService.IsAuthenticated(cookie);

        return isAuthenticated;

Need Your Help

GWT Button Click Enable/Disable Pattern -- GwtEvent assertLive() in dev mode


To avoid users clicking repetitively on the same button and by the same token send multiple requests to server, I have used the following pattern:

Add same value into string multiple times

c# string

I'm trying to make a simple tab space between words, using a dynamic ammount. How would I do this?