You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET中从HTML和JS调用同一Controller方法的404问题求助

Hey there! Let's troubleshoot that 404 error you're getting when calling PerformImportRosterData from JavaScript—since it works from your view, we just need to align a few things for JS to play nice with your controller action. Here's what to check and fix:

1. Verify Your Controller & Action Routing

First, make sure your routing setup matches the URL you're calling (https://example.org/deputy/PerformImportRosterData).

  • If you're using ASP.NET Core with attribute routing:
    • Add a route prefix to your controller class, then specify the action route:
      [Route("deputy")]
      public class DeputyController : Controller
      {
          [HttpPost("PerformImportRosterData")] // Explicitly maps POST to this URL
          public IActionResult PerformImportRosterData(YourParameterModel model)
          {
              // Your import logic here
          }
      }
      
  • If you're using convention-based routing (older MVC or Core without attribute routing):
    • Double-check your RouteConfig.cs (MVC) or Program.cs (Core) has a default route that includes the controller and action:
      // Example for ASP.NET Core
      app.MapControllerRoute(
          name: "default",
          pattern: "{controller=Home}/{action=Index}/{id?}");
      
    Ensure your controller is named DeputyController (since the URL uses deputy—controller names are case-insensitive but must end with "Controller").

2. Match the HTTP Verb

Your JavaScript is making a POST request, so your action must accept POST. Add the [HttpPost] attribute to your method (if you want it to accept both GET and POST for the view/JS, use [AcceptVerbs("GET", "POST")] instead):

[HttpPost]
public IActionResult PerformImportRosterData(...)
{
    // Logic
}

Without this, MVC might default to only allowing GET requests, which would cause a 404 for your POST call from JS.

3. Fix Parameter Binding

Make sure your JavaScript is sending data in a format your controller can parse:

  • If you're sending JSON (common for JS):
    • Set the Content-Type header to application/json in your JS request, and stringify your data.
    • Use [FromBody] in your controller to bind the JSON to a model:
      // Sample JS fetch call
      const importData = { param1: "value1", param2: "value2" };
      const csrfToken = document.querySelector('input[name="__RequestVerificationToken"]').value;
      
      fetch('/deputy/PerformImportRosterData', {
          method: 'POST',
          headers: {
              'Content-Type': 'application/json',
              'X-CSRF-Token': csrfToken // Critical for anti-forgery!
          },
          body: JSON.stringify(importData)
      })
      .then(response => response.json())
      .catch(error => console.error('Error:', error));
      
      [HttpPost]
      public IActionResult PerformImportRosterData([FromBody] ImportRosterModel model)
      {
          // Process model
          return Ok(new { success = true });
      }
      
  • If you're sending form data (like your view does):
    • Use FormData in JS and skip JSON stringify. Your controller can use [FromForm] or rely on default binding.

4. Don't Forget Anti-Forgery Tokens

ASP.NET automatically protects against CSRF attacks, which means your JS request needs to include the anti-forgery token that your view uses.

  • Add the token to your view (it's probably already there if your view form works, but confirm):
    <input name="__RequestVerificationToken" type="hidden" value="@Html.AntiForgeryToken()" />
    
  • Include this token in your JS request—either in the request header (as shown above) or as a field in your FormData.
  • For ASP.NET Core, you can also add [ValidateAntiForgeryToken] to your action to enforce token validation (it's enabled by default for form posts, but explicit is better).

5. Double-Check URL Spelling & Case

It sounds silly, but typos or case mismatches (especially on Linux servers, which are case-sensitive) can cause 404s. Make sure:

  • The controller name in the URL matches your controller class (e.g., DeputyController maps to /deputy/...)
  • The action name in the URL exactly matches your method name (PerformImportRosterData)

If you've gone through all these steps, your action should work seamlessly from both your view and JavaScript.

内容的提问来源于stack exchange,提问作者Josh Fletcher

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 09:24:33