简体   繁体   中英

400 Bad Request when trying Ajax call to Controller in ASP.NET MVC

So I've been struggling to do a simple request from a CSHTML page to a Controller in my ASP.NET MVC website application. I'm using Ajax to try a DELETE call:

$.ajax({
    url: "/company/delete",
    type: "DELETE",
    success: function (e) {
        showAlert('Success!');
    }
});

And just returning a JSON on the controller side:

public class CompanyController : BaseController
{
    protected readonly IHttpClientFactory _clientFactory;

    public CompanyController(IHttpClientFactory clientFactory)
    {
        _clientFactory = clientFactory;
    }

    [HttpDelete]
    [Route("company/delete")]
    public JsonResult DeleteCompany()
    {
        return Json("ok");
    }
}

BaseController.cs :

[Authorize(Policy = "IsLoggedIn")]
public class BaseController : Controller
{ }

Every other implementation I saw was something like this. I've tried using @Url.Action("DeleteCompany", "Company") as Ajax URL, removing route and requesting to /Company/DeleteSite , adding [AllowAnonymous] tag as I'm using authentication, nothing works. It will always return a 400 Bad Request error (at least it is not 404 ).

I didn't start the project, so I don't know if there is any other configurations to set and access the Controller from the View. Note that I can access my API from the Ajax and access the API from the Controller, but I'm not being successful with accessing the Controller from the View with Ajax.

It turns out it was bad IIS configuration. Adding a rule to accept every type of request worked.

This is the handler in web.config :

<add name="aspNetCore" path="*" verb="GET,HEAD,POST,DEBUG,DELETE,PUT" modules="AspNetCoreModuleV2" resourceType="Unspecified" requireAccess="None" />

Change your controller function return type to ActionResult instead of JsonResult

[HttpDelete]
[Route("company/delete")]
public ActionResult DeleteCompany()
{
    return Json("ok");
}

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