Część 10, badanie szczegółów i metod usuwania aplikacji ASP.NET CorePart 10, examine the Details and Delete methods of an ASP.NET Core app
Autor: Rick AndersonBy Rick Anderson
Otwórz kontroler filmu i Przeanalizuj Details
metodę:Open the Movie controller and examine the Details
method:
// GET: Movies/Details/5
public async Task<IActionResult> Details(int? id)
{
if (id == null)
{
return NotFound();
}
var movie = await _context.Movie
.FirstOrDefaultAsync(m => m.Id == id);
if (movie == null)
{
return NotFound();
}
return View(movie);
}
Aparat tworzenia szkieletu MVC, który utworzył tę metodę akcji, dodaje komentarz zawierający żądanie HTTP, które wywołuje metodę.The MVC scaffolding engine that created this action method adds a comment showing an HTTP request that invokes the method. W tym przypadku jest to żądanie GET z trzema segmentami adresów URL, Movies
kontrolerem, Details
metodą i id
wartością.In this case it's a GET request with three URL segments, the Movies
controller, the Details
method, and an id
value. Wycofaj te segmenty są zdefiniowane w Startup.cs.Recall these segments are defined in Startup.cs.
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
EF ułatwia wyszukiwanie danych przy użyciu FirstOrDefaultAsync
metody.EF makes it easy to search for data using the FirstOrDefaultAsync
method. Ważna funkcja zabezpieczeń wbudowana w metodę polega na tym, że kod sprawdza, czy metoda wyszukiwania znalazła film przed podjęciem próby wykonania jakichkolwiek czynności.An important security feature built into the method is that the code verifies that the search method has found a movie before it tries to do anything with it. Na przykład haker może wprowadzić błędy do witryny przez zmianę adresu URL utworzonego przez linki z http://localhost:{PORT}/Movies/Details/1
do czegoś takiego jak http://localhost:{PORT}/Movies/Details/12345
(lub innej wartości, która nie reprezentuje rzeczywistego filmu).For example, a hacker could introduce errors into the site by changing the URL created by the links from http://localhost:{PORT}/Movies/Details/1
to something like http://localhost:{PORT}/Movies/Details/12345
(or some other value that doesn't represent an actual movie). Jeśli nie zaznaczono filmu o wartości null, aplikacja zgłosi wyjątek.If you didn't check for a null movie, the app would throw an exception.
Przejrzyj Delete
metody i DeleteConfirmed
.Examine the Delete
and DeleteConfirmed
methods.
// GET: Movies/Delete/5
public async Task<IActionResult> Delete(int? id)
{
if (id == null)
{
return NotFound();
}
var movie = await _context.Movie
.FirstOrDefaultAsync(m => m.Id == id);
if (movie == null)
{
return NotFound();
}
return View(movie);
}
// POST: Movies/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(int id)
{
var movie = await _context.Movie.FindAsync(id);
_context.Movie.Remove(movie);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
Należy zauważyć, że HTTP GET Delete
Metoda nie usuwa określonego filmu, zwraca widok filmu, w którym można przesłać (HTTPPOST) usunięcie.Note that the HTTP GET Delete
method doesn't delete the specified movie, it returns a view of the movie where you can submit (HttpPost) the deletion. Wykonanie operacji usuwania w odpowiedzi na żądanie GET (lub w tym przypadku wykonanie operacji edycji, operacji tworzenia lub jakiejkolwiek innej operacji, która zmienia dane) powoduje otwarcie otworu zabezpieczeń.Performing a delete operation in response to a GET request (or for that matter, performing an edit operation, create operation, or any other operation that changes data) opens up a security hole.
[HttpPost]
Metoda, która usuwa dane, ma nazwę, DeleteConfirmed
Aby nadać metodzie post protokołu HTTP unikatowy podpis lub nazwę.The [HttpPost]
method that deletes the data is named DeleteConfirmed
to give the HTTP POST method a unique signature or name. Poniżej przedstawiono dwie sygnatury metod:The two method signatures are shown below:
// GET: Movies/Delete/5
public async Task<IActionResult> Delete(int? id)
{
// POST: Movies/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(int id)
{
Środowisko uruchomieniowe języka wspólnego (CLR) wymaga, aby przeciążone metody miały unikatowy podpis parametru (taka sama nazwa metody, ale inna lista parametrów).The common language runtime (CLR) requires overloaded methods to have a unique parameter signature (same method name but different list of parameters). Jednak w tym miejscu wymagane Delete
są dwie metody — jeden dla elementu get i jeden dla elementu post--oba mają taki sam podpis parametru.However, here you need two Delete
methods -- one for GET and one for POST -- that both have the same parameter signature. (Oba muszą akceptować jedną liczbę całkowitą jako parametr).(They both need to accept a single integer as a parameter.)
Istnieją dwa podejścia do tego problemu, jedną z nich jest nadanie metodom różnych nazw.There are two approaches to this problem, one is to give the methods different names. To właśnie mechanizm tworzenia szkieletu w poprzednim przykładzie.That's what the scaffolding mechanism did in the preceding example. Wprowadzamy jednak niewielki problem: ASP.NET mapuje segmenty adresu URL na metody akcji według nazwy, a jeśli zmienisz nazwę metody, routing zwykle nie będzie mógł znaleźć tej metody.However, this introduces a small problem: ASP.NET maps segments of a URL to action methods by name, and if you rename a method, routing normally wouldn't be able to find that method. To rozwiązanie jest widoczne w przykładzie, który polega na dodaniu ActionName("Delete")
atrybutu do DeleteConfirmed
metody.The solution is what you see in the example, which is to add the ActionName("Delete")
attribute to the DeleteConfirmed
method. Ten atrybut wykonuje mapowanie dla systemu routingu w taki sposób, aby adres URL, który zawiera/Delete/dla żądania POST, znajdował DeleteConfirmed
metodę.That attribute performs mapping for the routing system so that a URL that includes /Delete/ for a POST request will find the DeleteConfirmed
method.
Inna częsta obejście dla metod, które mają identyczne nazwy i podpisy, polega na sztucznej zmianie sygnatury metody POST w celu uwzględnienia dodatkowego parametru (nieużywane).Another common work around for methods that have identical names and signatures is to artificially change the signature of the POST method to include an extra (unused) parameter. To właśnie zrobiono w poprzednim wpisie po dodaniu notUsed
parametru.That's what we did in a previous post when we added the notUsed
parameter. Tę samą czynność można wykonać w tym miejscu dla [HttpPost] Delete
metody:You could do the same thing here for the [HttpPost] Delete
method:
// POST: Movies/Delete/6
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Delete(int id, bool notUsed)
Publikowanie na platformie AzurePublish to Azure
Aby uzyskać informacje na temat wdrażania na platformie Azure, zobacz Samouczek: Tworzenie aplikacji ASP.NET Core i SQL Database w Azure App Service.For information on deploying to Azure, see Tutorial: Build an ASP.NET Core and SQL Database app in Azure App Service.