无法将发布数据从Ajax发送到asp.net核心Web API?

时间:2019-12-13 15:56:17

标签: ajax asp.net-core-webapi

我需要向asp.net核心网络api中定义的post方法发送ajax请求,如下所示:

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

这是UserInfos模型:

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; }
}

我使用postman进行了测试,方法是将标头设置为'Content-Type':'application / json',然后在正文中选择raw并传递此json对象:

 {

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

我可以使用它,但是当我从ajax调用它时,我得到了 BAD REQUEST 400 ,这是我的ajax代码:

        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);
            }
        });

注意 asp.net核心Web api和ajax代码位于不同的服务器中,因此在不同的域中,我已在 startup中启用了对我的域的CORS访问权限.cs ,因此通常不会触发问题。 我也成功向该Web服务发出了获取请求

2 个答案:

答案 0 :(得分:1)

测试这些,在每个构建项目之后,也许其中一个工作正常:

  1. 删除[FromBody]

2。在控制器类上方,请使用此[ApiController]

3。测试

$.ajax({
        url:'http://test.example.fr/wsexample/api/Entreprise/Inscription',
        data:{
                "firstname" :"ahmed",
                "lastname":"haddad", 
                "email":"haddad-a@live.fr" ,
                "domainName":"easyappointments-master" ,
                "phoneNumber":"25276164", 
                "address":"ariana" ,
                "city":"grand tunis",
                "zip_code":"4100" ,
               },
        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);
        }
    });

4。将[IgnoreAntiforgeryToken]放在操作结果的顶部

答案 1 :(得分:1)

我认为该错误与您的

有关
ContentType:'application/json',

应该是

contentType: 'application/json',

并删除此

dataType: "json"

jQuery.ajax尝试根据指定的dataType参数或服务器发送的Content-Type标头转换响应主体。如果转换失败(例如JSON / XML无效),则会触发错误回调。在此处阅读更多信息:Ajax request returns 200 OK, but an error event is fired instead of success

我可以使用它

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>
}

控制台:

the request is success the data is value 1