Ricardo Fontana Ricardo Fontana - 1 year ago 229
C# Question

Command equivalent to AntiForgery.Validate() in asp.net-core

Exists, in asp.net-core, a command similar to

to validate antiforgery token in the action body?

Code example in dotnet 4.5.1:

public ActionResult Index()
if (!User.Identity.IsAuthenticated)

// rest of action

Answer Source

Antiforgery token validation can be done automatically using filter attributes in your controllers.

  • Use [AutoValidateAntiforgeryToken] to validate the token on all "unsafe" methods. (Methods other than GET, HEAD, TRACE, OPTIONS).
  • Use [ValidateAntiforgeryToken] to always validate the token
  • Use [IgnoreAntiforgeryToken] to ignore token validation

You can combine these attributes to achieve the granularity you need. For example:

//Validate all 'unsafe' actions except the ones with the ignore attribute
public class MyApi: Controller
    public IActionResult DoSomething(){ }
    public IActionResult DoSomethingElse(){ }

    public IActionResult DoSomethingSafe(){ }

//Validate only explicit actions
public class ArticlesController: Controller
    public IActionResult Index(){ }

    public IActionResult Create(){ }

I have noticed the documentation isnt fully ready in the docs site, but you can see a draft of it in the github issue.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download