0

I need to send an ajax request to a post method defined in my asp.net core web api as below :

    // POST: api/Entreprise/Inscription
    [HttpPost("Inscription")]
    public IActionResult Post([FromBody] UserInfos value)
    {
        return Ok("value 1");
    } 

and this is UserInfos model:

public class UserInfos
{
    public string firstname { get; set; }
    public string lastname { get; set; }
    public string email { get; set; }
    public string domainName { get; set; }

    public string phoneNumber {get;set;}
    public string address { get; set; }
    public string city { get; set; }
    public string zip_code { get; set; }
}

I tested it with postman , by setting the header as 'Content-Type':'application/json' and in the body choosed raw and passed this json object :

 {

    "firstname" :"ahmed",
    "lastname":"haddad", 
    "email":"haddad-a@live.fr" ,
    "domainName":"easyappointments-master" ,
    "phoneNumber":"25276164", 
    "address":"ariana" ,
    "city":"grand tunis",
    "zip_code":"4100" 
  }

and i get it to work, however when i call it from ajax i get BAD REQUEST 400 , this is my ajax code:

        var newData={
                    "firstname" :"ahmed",
                    "lastname":"haddad", 
                    "email":"haddad-a@live.fr" ,
                    "domainName":"easyappointments-master" ,
                    "phoneNumber":"25276164", 
                    "address":"ariana" ,
                    "city":"grand tunis",
                    "zip_code":"4100" ,
                   };

        var dataJson= JSON.stringify(newData);

        $.ajax({
            url:'http://test.example.fr/wsexample/api/Entreprise/Inscription',
            dataType:'json',
            data:dataJson,
            ContentType:'application/json',
            type:'post',
            success:function(data,status){
                console.log('the request is '+status+' the data is '+data);
            },
            error:function(html,status,error){
                console.log('the request is '+error);
            }
        });

Note: the asp.net core web api and the ajax codes are in different servers ,so different domains , i have enabled the access to CORS for my domain in startup.cs , so normally that shouldn't trigger an issue. also i have made succeded get requests to that webservice

A.HADDAD
  • 1,809
  • 4
  • 26
  • 51

2 Answers2

2

I think the error has to do with your

ContentType:'application/json',

It should be

contentType: 'application/json',

and also remove this

dataType: "json"

jQuery.ajax attempts to convert the response body depending on the specified dataType parameter or the Content-Type header sent by the server. If the conversion fails (e.g. if the JSON/XML is invalid), the error callback is fired. Read more here: Ajax request returns 200 OK, but an error event is fired instead of success

I got this to work:

EnterpriseController.cs

public class EnterpriseController : Controller
{
    public async Task<IActionResult> Index()
    {
        return View();
    }

    [HttpPost]
    [Route("api/[controller]/Inscription")]
    public IActionResult Post([FromBody] UserInfos value)
    {
        return Ok("value 1");
    }
}

Index.cshtml

@section Scripts {
    <script>
        $(document).ready(function () {
            var newData = {
                "firstname": "ahmed",
                "lastname": "haddad",
                "email": "haddad-a@live.fr",
                "domainName": "easyappointments-master",
                "phoneNumber": "25276164",
                "address": "ariana",
                "city": "grand tunis",
                "zip_code": "4100"
            }

            $.ajax({
                url: '/api/Enterprise/Inscription/',
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify(newData),
                success: function (data, status) {
                    console.log('the request is ' + status + ' the data is ' + data);
                },
                error: function (html, status, error) {
                    console.log('the request is ' + error);
                }
            });
        });
    </script>
}

Console:

the request is success the data is value 1
Joel Wiklund
  • 1,697
  • 2
  • 18
  • 24
  • yes that work , but i don't understand how ? dataType is the type of the response , did you mean that the type of the response is not json here ,that is why it trigger an error – A.HADDAD Dec 16 '19 at 07:27
  • Please read the accepted answer here https://stackoverflow.com/questions/6186770/ajax-request-returns-200-ok-but-an-error-event-is-fired-instead-of-success – Joel Wiklund Dec 16 '19 at 07:36
  • Another alternative is to return a Json(new { Data = "value 1" }) instead of Ok("value 1"). https://stackoverflow.com/questions/227624/asp-net-mvc-controller-actions-that-return-json-or-partial-html – Joel Wiklund Dec 16 '19 at 07:45
1
  1. removing [FromBody] from the controller

2.below the controller class use this [ApiController]

3.use this for post

$.ajax({
        url:'http://test.example.fr/wsexample/api/Entreprise/Inscription',
        data:JSON.stringify({
                "firstname" :"ahmed",
                "lastname":"haddad", 
                "email":"haddad-a@live.fr" ,
                "domainName":"easyappointments-master" ,
                "phoneNumber":"25276164", 
                "address":"ariana" ,
                "city":"grand tunis",
                "zip_code":"4100" ,
               }),
        type:'post',
     headers: {                    
                    'Content-Type': 'application/json'
                },
        success:function(data,status){
            console.log('the request is '+status+' the data is '+data);
        },
        error:function(html,status,error){
            console.log('the request is '+error);
        }
    });

4.put [IgnoreAntiforgeryToken] top of your actionresult

javidasd
  • 1,126
  • 13
  • 18