skip to Main Content

A little strange. If the following programs are all in the ASP.NET Core 6 MVC project, there will be no problem.

But if you separate the program. Ajax is in the ASP.NET Core 6 MVC project, and the C# function is in the ASP.NET Core 6 Web API project. When Ajax calls a C# function, I always get 400 bad request error.

How to solve this problem?

Javascript (Ajax):

    var data = {
        value1: "ProposerMail",
        value2: "ExpextMail",
    };

    var url = "https://localhost:7253/Values/api/Test666";
    
    $.ajax({
        url: url,
        type: 'POST',                   
        data: data,             
    }).done(function (data) {

        var lsTemp;
        lsTemp = "AAA";

    })
        .fail(function (jqXHR, textStatus, errorThrown) {

            alert(jqXHR.status);
            alert(textStatus);
            alert(errorThrown);

        });
     

C#:

   [HttpPost]
   [Route("api/Test666/")]
   public IActionResult Test666(string value1, string value2)
   {
      return Ok(value1);
   }

I can’t find answers to related questions on the website, so I hope someone can provide advice to help solve the problem.

2

Answers


  1. Chosen as BEST ANSWER

    Thanks for everyone's help, this problem has been solved

    Js::
    
    [HttpPost]
    [Route("api/Test666")]
    public IActionResult Test666([FromBody] MyModel model) // Use a model class
    {
        return Ok(model.Value1); // Return the value1 property
    }
    
    public class MyModel
    {
        public string Value1 { get; set; }
        public string Value2 { get; set; }
    }
    
    C#::
    var lsTemp;
     lsTemp = "AAAA";
    
     var data = {
         value1: "ProposerMail",
         value2: "ExpextMail",
     };
    
     var url = "https://localhost:7253/Values/api/Test666"; // Remove "Values" from the route
     //https://localhost:7253/Values/api/Test666
     $.ajax({
         url: url,
         type: 'POST',
         contentType: 'application/json', // Set the content type
         data: JSON.stringify(data), // Serialize the data
     }).done(function (response) {
         var lsTemp = "AAA";
         console.log(response); // Log the response
     }).fail(function (jqXHR, textStatus, errorThrown) {
         alert(jqXHR.status);
         alert(textStatus);
         alert(errorThrown);
     });
    

  2. You have to include the contentType in an Ajax request to specify the MIME-type (which will be sent in the Content-Type header)

    $.ajax({
            url: url,
            type: "POST",                   
            data: data,
            contentType: "application/json"
    
        })
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search