Can't send Post Data from Ajax to asp.net core web api?

北战南征 提交于 2021-01-29 09:47:28

问题


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


回答1:


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



回答2:


  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



来源:https://stackoverflow.com/questions/59325946/cant-send-post-data-from-ajax-to-asp-net-core-web-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!