简体   繁体   English

在 asp.net mvc Core 2.1 中调用 POST 方法时出现错误 404

[英]Error 404 when calling POST method in asp.net mvc Core 2.1

I'm working on my first MVC Core 2.1 app and encountered problem (i guess with the routing).我正在开发我的第一个 MVC Core 2.1 应用程序并遇到问题(我猜是路由问题)。 When calling a POST method shown below:调用如下所示的 POST 方法时:

    [HttpPost]
    public RedirectToActionResult Remove(int id)
    {
        Product p = _repository.Products.Where(x => x.Id == id).FirstOrDefault();
        _repository.Products.Remove(p);
        _repository.SaveChanges();
        return RedirectToAction("Index");
    }

i get the error 404 page not found.我收到错误 404 页面未找到。 Below tag located in a partial view which sends the request:下面的标签位于发送请求的部分视图中:

<a method="POST" asp-controller="Product" asp-action="Remove" asp-route-id="@Model.Id" class="btn btn-danger">Delete</a>

it generates " https://localhost:44398/Product/Remove/3 " (on product with id 3) which seems to be matching它生成“ https://localhost:44398/Product/Remove/3 ”(在 id 为 3 的产品上),这似乎是匹配的

I'm using default routing我正在使用默认路由

app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });

also, if i change this same method from POST to get (getting rid of the database code) i'm able to access it另外,如果我将相同的方法从 POST 更改为 get(摆脱数据库代码),我就可以访问它

    [HttpGet]
    public RedirectToActionResult Remove(int id)
    {

        return RedirectToAction("Index");
    }

I bet I've made some stupid mistake, but I'm stuck with it and can't find the answer.我敢打赌我犯了一些愚蠢的错误,但我坚持下去,找不到答案。 Any help will be appreciated!任何帮助将不胜感激!

First of all, why would you need Post if you are passing just an Id through query string?首先,如果您只是通过查询字符串传递一个 Id,为什么还需要 Post 呢?

Also, if i recall correctly Post you need to setup Content-Type Headers when calling post verb.另外,如果我没记错的话,你需要在调用 post 动词时设置 Content-Type 标题。

You can try like below-您可以尝试如下 -

<form method="post">
        <input name="id" type="text" value="2" />
        <button type="submit" asp-controller="Product" asp-action="Remove">Click Me </button>
</form>

This is one way to pass the data to the action using form POST.这是使用表单 POST 将数据传递给操作的一种方法。 Model binding automatically binds the data from the form to the action parameters. Model 绑定自动将表单中的数据绑定到操作参数。 The name of the input tag is used for binding the data dynamically.输入标签的名称用于动态绑定数据。

I hope this helps.我希望这有帮助。

HTTP POST requests supply additional data from the client (browser) to the server in the message body. HTTP POST请求在消息正文中从客户端(浏览器)向服务器提供附加数据。 In contrast, GET requests include all required data in the URL.相比之下, GET请求包括 URL 中的所有必需数据。 Forms in HTML can use either method by specifying method="POST" or method="GET" (default) in the HTML中的Forms可以通过在element.元素。 The method specified determines how form data is submitted to the server.指定的方法确定表单数据如何提交到服务器。 When the method is GET, all form data is encoded into the URL, appended to the action URL as query string parameters.当方法为 GET 时,所有表单数据都被编码到 URL 中,作为查询字符串参数附加到操作 URL 中。 With POST, form data appears within the message body of the HTTP request.使用 POST,表单数据出现在 HTTP 请求的消息正文中。

Refer to the following links for more details on the differences between Get and Post: https://stackoverflow.com/a/3477374/10201850有关 Get 和 Post 之间差异的更多详细信息,请参阅以下链接: https://stackoverflow.com/a/3477374/10201850

https://www.diffen.com/difference/GET-vs-POST-HTTP-Requests https://www.diffen.com/difference/GET-vs-POST-HTTP-Requests

One thing: If you are using persisting data and want to delete a object that his primary key is in another table as FK you must need to make a logic erase, thats why you are not able to delete, if not your problem: I´m newbie also and I´m working on .NET Core 3 so my routes looks like:一件事:如果您正在使用持久数据并想要删除他的主键作为 FK 在另一个表中的 object,您必须进行逻辑擦除,这就是您无法删除的原因,如果不是您的问题:I´我也是新手,我正在研究 .NET Core 3,所以我的路线看起来像:

 app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute(
                name: null,
                pattern: "{category}/Page{productPage:int}",
                defaults: new { controller = "Product", action = "List" }
            );
            endpoints.MapControllerRoute(
                name: null,
                pattern: "Page{productPage:int}",
                defaults: new
                {
                    controller = "Product",
                    action = "List",
                    productPage = 1
                }
                 ...
            );
// And my default:
            endpoints.MapControllerRoute("default", "{controller=Product}/{action=List}/{id?}");

This is a form for one of my projects:这是我的一个项目的表格:

<form asp-action="Delete" method="post">
                    <a asp-action="Edit" class="btn btn-sm btn-warning"
                       asp-route-productId="@item.ProductID">
                        Edit
                    </a>
                    <input type="hidden" name="ProductID" value="@item.ProductID" />
                    <button type="submit" class="btn btn-danger btn-sm">
                        Delete
                    </button>
                </form>

There´sa difference here: Mine: asp-route-productId="@item.ProductID" Yours: asp-route-id="@Model.Id" How did you call it?这里有一个区别:我的: asp-route-productId="@item.ProductID"你的: asp-route-id="@Model.Id"你怎么称呼它?

This is my Edit method:这是我的编辑方法:

 [HttpPost]
        public IActionResult Delete(int productId)
        {
            Product deletedProduct = repository.DeleteProduct(productId);
            if(deletedProduct != null)
            {
                TempData["message"] = $"{deletedProduct.Name} ha sido borrado";
            }
            return RedirectToAction("Index");
        }
    }

And the last call:最后一个电话:

public Product DeleteProduct(int productID)
        {
            Product dbEntry = context.Products
                .FirstOrDefault(p => p.ProductID == productID);
            if(dbEntry != null)
            {
                context.Products.Remove(dbEntry);
                context.SaveChanges();
            }
            return dbEntry;
        }

You can try to: Change to IActionResult instead RedirectToActionResult.您可以尝试:更改为 IActionResult 而不是 RedirectToActionResult。

if is working before, resend web config file to server, it will reset application.如果之前工作正常,将 web 配置文件重新发送到服务器,它将重置应用程序。 I guess in publish web config file should be latest file.我猜在发布 web 配置文件应该是最新文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Asp.Net Core WEB API 错误 404 调用方法 - Asp.Net Core WEB API error 404 calling method 当 ASP.NET Core MVC 中出现 404 错误时,重定向不起作用 - Redirection is not working when there is 404 error in ASP.NET Core MVC ASP.Net Core 2.1/WebAPI 应用程序:“未找到 HTTP 404”使用 [授权] 调用 REST url - ASP.Net Core 2.1/WebAPI app: "HTTP 404 not found" calling a REST url with [Authorize] 在针对 Azure AD 注销 ASP.NET Core MVC 应用程序时如何修复错误 404? - How to fix error 404 when logging out on an ASP.NET Core MVC app against Azure AD? ASP.NET WebApi Post方法 - 404传递参数时 - ASP.NET WebApi Post Method - 404 When Passing Parameters ASP.NET Core 2.1 MVC 使用 XMLHttpRequest 将数据从 JavaScript 发送到 Action 方法 - ASP.NET Core 2.1 MVC send data from JavaScript to Action method using XMLHttpRequest 发布到IIS 7.5时ASP.NET Core 404错误 - ASP.NET Core 404 Error When Published to IIS 7.5 ASP.NET Core 2.1 在一个schedule中调用Rest API - ASP.NET Core 2.1 Calling Rest API in a schedule ASP.NET 核心 MVC 调用 API - ASP.NET Core MVC calling an API ASP.NET MVC 5从Javascript Error调用控制器方法 - ASP.NET MVC 5 calling controller method from Javascript Error
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM