In ASP.NET MVC 5, how does the framework know that a POST request comes from its own web page?

Let me explain in more detail.

I study and test using ASP.NET MVC 5 using Visual Studio 2017. From what I understand, the control "Actions" or methods are displayed according to the route format in "RouteConfig.cs", which makes everything accessible for the web queries.

In the case of a simple GET method that returns a view like this:

// GET: Movies/Create
public ActionResult Create()
{
    return View();
}

I would need to enter the correct url and I got a view.

But in the case of reasonable POST actions, such as deleting data input, how should the controller make sure that the POST request is valid, which comes from one of its own views instead of an unknown web page? With the assumption that the action needs only to be matched with the corresponding route that should be called.

Using code from one of Microsoft's tutorials as an example:

public class MoviesController : Controller
{
    private MovieDBContext db = new MovieDBContext();

    /*
    Bunch of Other GET Actions
    */

    // POST: Movies/Delete/5
    [HttpPost, ActionName("Delete")]
    [ValidateAntiForgeryToken]
    public ActionResult DeleteConfirmed(int id)
    {
        Movie movie = db.Movies.Find(id);
        db.Movies.Remove(movie);
        db.SaveChanges();
        return RedirectToAction("Index");
    }

    /*
    Bunch of Other GET Actions
    */

}

How does this controller achieve this? If not, how can this be achieved?

+4
source share
2 answers

This is the purpose of the Anti-Forgery token that you test by decorating the action method with an attribute ValidateAntiForgeryToken. Your view will need to include an anti-fake token, which will be checked using the method@Html.AntiForgeryToken() HtmlHelper

+2

, ValidateAntiForgeryToken . , MVC , , , "MyTest", - MyTestController. , MyTest, MyTest, MyTest. , . !

0

Source: https://habr.com/ru/post/1689030/


All Articles