HI WELCOME TO SIRIS

Part 23 - Why deleting database records using get request is bad

Leave a Comment
we will discuss, why deleting database records using GET request is bad.

First let's discuss, how to delete data in MVC using GET request and then we will discuss, why it is bad to do so.

Step 1: Create a stored procedure to delete employee data by "ID"
Create procedure spDeleteEmployee
@Id int
as
Begin
Delete from tblEmployee 
where Id = @Id
End

Step 2: Add the following DeleteEmployee() method to "EmployeeBusinessLayer.cs" file in "BusinessLayer" project. This method calls the stored procedure "spDeleteEmployee" that we just created.
public void DeleteEmployee(int id)
{
    string connectionString =
            ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;

    using (SqlConnection con = new SqlConnection(connectionString))
    {
        SqlCommand cmd = new SqlCommand("spDeleteEmployee", con);
        cmd.CommandType = CommandType.StoredProcedure;

        SqlParameter paramId = new SqlParameter();
        paramId.ParameterName = "@Id";
        paramId.Value = id;
        cmd.Parameters.Add(paramId);

        con.Open();
        cmd.ExecuteNonQuery();
    }
}

Step 3: Add the following "DELETE" controller action method to "EmployeeController".
public ActionResult Delete(int id)
{
    EmployeeBusinessLayer employeeBusinessLayer = 
        new EmployeeBusinessLayer();
    employeeBusinessLayer.DeleteEmployee(id);
    return RedirectToAction("Index");
}

Run the application and navigate to "Index" action. Click the "Delete" link. This issues "GET" request to the following URL, and deletes the record.
http://localhost/MVCDemo/Employee/Delete/1

Deleting database records using GET request opens a security hole and is not recommended by Microsoft. Just imagine what can happen if there is an image tag in a malicious email as shown below. The moment we open the email, the image tries to load and issues a GET request, which would delete the data.
<img src="http://localhost/MVCDemo/Employee/Delete/2" />

Also, when search engines index your page, they issue a GET request which would delete the data. In general GET request should be free of any side-effects, meaning it should not change the state.  

Deletes should always be performed using a POST request.

0 comments:

Post a Comment

Note: only a member of this blog may post a comment.