C# POST提交表单重定向后找不到控制器方法,出现404错误如何解决?
Hey there, let's figure out why you're getting that 404 error when submitting your form. The request URL you shared (http://localhost:52008/InternalController/UpdateCardFormPost) already gives a big clue—let's break down the most likely issues and fixes:
In ASP.NET MVC, the routing system automatically strips the Controller suffix from your controller class name. So your InternalController should be referenced as Internal in the URL, not InternalController. That's why the server can't find the right controller—there's no route matching InternalController/UpdateCardFormPost.
To fix this:
- If you're writing the form action manually, change it to
/Internal/UpdateCardFormPost - Better yet, use the
Html.BeginFormhelper to avoid typos entirely:@using (Html.BeginForm("UpdateCardFormPost", "Internal", FormMethod.Post)) { // Your form fields here @Html.AntiForgeryToken() // Make sure this matches the [ValidateAntiForgeryToken] attribute on your action <button type="submit">Submit</button> }
Double-check your route setup (usually in RouteConfig.cs or Startup.cs if you're using a newer MVC version) to ensure the default route allows access to your action. The standard default route looks like this:
routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } );
If you've added custom routes that override this, make sure they don't block access to Internal/UpdateCardFormPost.
Make sure your UpdateCardFormPost method is correctly configured:
- It must be marked with
[HttpPost](you mentioned this, but double-check it's not missing) - If you're using
[ValidateAntiForgeryToken], your view must include@Html.AntiForgeryToken()(missing this would cause a validation error, not 404, but it's good to confirm) - The method must be
publicand return anActionResult(or a derived type likeRedirectToRouteResult) - Ensure the method's parameters match the form data you're submitting (e.g., if you're passing a
CardViewmodel, the form fields should have names that match the model's properties)
Make sure your InternalController inherits from System.Web.Mvc.Controller (or ControllerBase for newer MVC versions) and that the class name ends with Controller (which it does, since you have InternalController). If the inheritance is missing, the routing system won't recognize it as a valid controller.
The most likely fix here is correcting the form action to use Internal instead of InternalController—that's the most common mistake that leads to this exact 404 error.
内容的提问来源于stack exchange,提问作者Rilcon42

