简体   繁体   中英

HttpDelete method in .net MVC returns error 405 - method not allowed

All online info states to make changes to web.config file, but, as I understand, web.config file doesn't exist in the newer versions of .net mvc. What to do to allow httpDelete method then?

(I've created delete method in my controller that calls MySQL 'delete from table' method)

code:

[HttpDelete]
        public ActionResult Delete() //string id
        {
            connectionString();
            conn.Open();
            com.Connection = conn;

            var userId = HttpContext.Session.GetString("userId");

            var stm = "Delete from lex_reminders where reminder_id=@id"; //" + id + ";
            var cmd = new MySqlCommand(stm, conn);
            cmd.Parameters.AddWithValue("@id", 25);
            int res = cmd.ExecuteNonQuery();

            if (res>0)
            {
                conn.Close();
                Create(userId);
                return View("Create");
            }
            else
            {
                conn.Close();
                return View("Error");
            }
        }

Note that the HTTP Get``Delete method doesn't delete the specified record, it should return a view of that entity where you can submit (HttpPost) the deletion.. 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 . read this document for security hole: http://stephenwalther.com/archive/2009/01/21/asp-net-mvc-tip-46-ndash-donrsquot-use-delete-links-because See below example for Delete method with HtpPost:

// GET: /Movies/Delete/5
public ActionResult Delete(int? id)
{
    if (id == null)
    {
        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
    }
    Movie movie = db.Movies.Find(id);
    if (movie == null)
    {
        return HttpNotFound();
    }
    return View(movie);
}

// 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");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM