MeanGreen
MeanGreen

Reputation: 3305

MVC AntiForgeryToken exception - Handle globally

In my MVC project, there are multiple actions where security between requests and responses is increased with the [ValidateAntiForgeryToken] attribute. This works fine. Problems arise when a user keeps the page open for several minutes (I assume 20, (Session State timeout?)) and then sends a request to the server. This causes an error, because the token sent back no longer matches the token on the server.

Reading this question, it can be solved by adding a HandleError attribute on each specific action that uses [ValidateAntiForgeryToken].

Is there a way to set this globally for the entire website? I'd hate setting it on every action separately.

Upvotes: 2

Views: 2462

Answers (1)

frikinside
frikinside

Reputation: 1244

You can regsiter an ActionFilter globally in global.asax on Application_Start() event.

protected void Application_Start()
{ 
    // Register global filter
    GlobalFilters.Filters.Add(new HandleErrorAttribute());

    RegisterGlobalFilters(GlobalFilters.Filters);
    RegisterRoutes(RouteTable.Routes);
}

Upvotes: 2

Related Questions