Reputation: 1478
Allow me to explain in more detail.
I've been learning and testing around with ASP.NET's MVC 5 using Visual Studio 2017. From what I understand, a Controller's "Actions" or methods are mapped according to a route format in "RouteConfig.cs", making all public methods accessible to web requests.
In the case of a simple GET method that returns a View, like this one:
// GET: Movies/Create
public ActionResult Create()
{
return View();
}
I would only need to enter the correct URL and I have obtained the View.
But in the case of sensible POST actions like deleting a data-entry, how does the controller make sure that the POST request is a valid one that comes from one of its own Views, instead of an unknown webpage? With the assumption that an action only need to be mapped to a matching route to be called.
Using a code sourced 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 it be achieved?
Upvotes: 4
Views: 69
Reputation: 721
Based on your example, ValidateAntiForgeryToken will do this job. If a bit more explanation, MVC has its own disciplined that once you create a new controller which name is "MyTest", naming convention is MyTestController. It means if you create a view for MyTest controller, a folder with MyTest should be created under View and where MyTest's views are supposed to be kept. I hope you would get my explanation. Enjoy coding !
Upvotes: 0
Reputation: 16553
That's the purpose of the Anti-Forgery token, which you're validating by decorating the action method with the ValidateAntiForgeryToken
attribute. Your view will need to include an anti-forgery token to be validated via the @Html.AntiForgeryToken()
HtmlHelper
method
Upvotes: 2