---
title: "How to call @html.AntiForgeryToken in ASP.NET Web API"  
description: "How to call @html.AntiForgeryToken in ASP.NET Web API"  
author: "ICSM Computer"  
published: 2025-06-10  
updated: 2025-06-10  
canonical: https://www.mindstick.com/interview/34225/how-to-call-html-antiforgerytoken-in-asp-dot-net-web-api  
category: "c#"  
tags: ["api(s)"]  
reading_time: 4 minutes  

---

# How to call @html.AntiForgeryToken in ASP.NET Web API

In **ASP.NET Web API (not MVC)**, `@Html.AntiForgeryToken()` **does not apply directly** because Web API does **not use Razor views** or MVC forms by default.

However, you can **integrate anti-forgery protection into Web API** by **manually validating anti-forgery tokens** for APIs that are accessed via AJAX (e.g., from MVC views or SPAs).

## Goal: Use Anti-Forgery Token in Web API

### Step 1: Generate the Token in MVC View

If your front-end uses Razor (MVC view), generate the anti-forgery token using:

```plaintext
@Html.AntiForgeryToken()
```

This emits **two things**:

1. A hidden form field: `__RequestVerificationToken`
2. A cookie: `__RequestVerificationToken`

### Step 2: Send Token with AJAX Request

In JavaScript, extract the token from the cookie or form and send it as a header:

```javascript
// Get the anti-forgery token from the form or cookie
var token = $('input[name="__RequestVerificationToken"]').val();

$.ajax({
    url: '/api/account/secure',
    type: 'POST',
    headers: {
        'RequestVerificationToken': token
    },
    data: { /* your payload */ },
    success: function (response) {
        // handle success
    }
});
```

### Step 3: Validate the Token in Web API

Create a **custom filter attribute** to validate the anti-forgery token:

```cs
using System.Web;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
using System.Web.Helpers;

public class ValidateAntiForgeryTokenAttribute : AuthorizationFilterAttribute
{
    public override void OnAuthorization(HttpActionContext actionContext)
    {
        var headers = actionContext.Request.Headers;

        if (headers.Contains("RequestVerificationToken"))
        {
            try
            {
                var cookieToken = "";
                var formToken = headers.GetValues("RequestVerificationToken").FirstOrDefault();

                if (HttpContext.Current.Request.Cookies["__RequestVerificationToken"] != null)
                {
                    cookieToken = HttpContext.Current.Request.Cookies["__RequestVerificationToken"].Value;
                }

                AntiForgery.Validate(cookieToken, formToken);
            }
            catch (HttpAntiForgeryException ex)
            {
                throw new HttpResponseException(System.Net.HttpStatusCode.Forbidden);
            }
        }
        else
        {
            throw new HttpResponseException(System.Net.HttpStatusCode.Forbidden);
        }
    }
}
```

### Step 4: Apply the Attribute to API Methods

```cs
[ValidateAntiForgeryToken]
public class AccountController : ApiController
{
    [HttpPost]
    public IHttpActionResult Secure(SomeModel model)
    {
        // Only reached if anti-forgery token is valid
        return Ok("Request valid");
    }
}
```

## Summary

| Component | Purpose |
| --- | --- |
| `@Html.AntiForgeryToken()` | Renders hidden input and cookie |
| Custom filter | Validates token on Web API |
| JavaScript header | Sends token with AJAX |
| `AntiForgery.Validate(cookie, token)` | Validates tokens on server |

## Answers

### Answer by ICSM Computer

In **ASP.NET Web API (not MVC)**, `@Html.AntiForgeryToken()` **does not apply directly** because Web API does **not use Razor views** or MVC forms by default.

However, you can **integrate anti-forgery protection into Web API** by **manually validating anti-forgery tokens** for APIs that are accessed via AJAX (e.g., from MVC views or SPAs).

## Goal: Use Anti-Forgery Token in Web API

### Step 1: Generate the Token in MVC View

If your front-end uses Razor (MVC view), generate the anti-forgery token using:

```plaintext
@Html.AntiForgeryToken()
```

This emits **two things**:

1. A hidden form field: `__RequestVerificationToken`
2. A cookie: `__RequestVerificationToken`

### Step 2: Send Token with AJAX Request

In JavaScript, extract the token from the cookie or form and send it as a header:

```javascript
// Get the anti-forgery token from the form or cookie
var token = $('input[name="__RequestVerificationToken"]').val();

$.ajax({
    url: '/api/account/secure',
    type: 'POST',
    headers: {
        'RequestVerificationToken': token
    },
    data: { /* your payload */ },
    success: function (response) {
        // handle success
    }
});
```

### Step 3: Validate the Token in Web API

Create a **custom filter attribute** to validate the anti-forgery token:

```cs
using System.Web;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
using System.Web.Helpers;

public class ValidateAntiForgeryTokenAttribute : AuthorizationFilterAttribute
{
    public override void OnAuthorization(HttpActionContext actionContext)
    {
        var headers = actionContext.Request.Headers;

        if (headers.Contains("RequestVerificationToken"))
        {
            try
            {
                var cookieToken = "";
                var formToken = headers.GetValues("RequestVerificationToken").FirstOrDefault();

                if (HttpContext.Current.Request.Cookies["__RequestVerificationToken"] != null)
                {
                    cookieToken = HttpContext.Current.Request.Cookies["__RequestVerificationToken"].Value;
                }

                AntiForgery.Validate(cookieToken, formToken);
            }
            catch (HttpAntiForgeryException ex)
            {
                throw new HttpResponseException(System.Net.HttpStatusCode.Forbidden);
            }
        }
        else
        {
            throw new HttpResponseException(System.Net.HttpStatusCode.Forbidden);
        }
    }
}
```

### Step 4: Apply the Attribute to API Methods

```cs
[ValidateAntiForgeryToken]
public class AccountController : ApiController
{
    [HttpPost]
    public IHttpActionResult Secure(SomeModel model)
    {
        // Only reached if anti-forgery token is valid
        return Ok("Request valid");
    }
}
```

## Summary

| Component | Purpose |
| --- | --- |
| `@Html.AntiForgeryToken()` | Renders hidden input and cookie |
| Custom filter | Validates token on Web API |
| JavaScript header | Sends token with AJAX |
| `AntiForgery.Validate(cookie, token)` | Validates tokens on server |


---

Original Source: https://www.mindstick.com/interview/34225/how-to-call-html-antiforgerytoken-in-asp-dot-net-web-api

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
