无法将Post Data从Ajax发送到asp.net核心Web API? [英] Can't send Post Data from Ajax to asp.net core web api?

查看:105
本文介绍了无法将Post Data从Ajax发送到asp.net核心Web API?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

这是UserInfos模型:

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

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

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

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

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

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

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

推荐答案

我认为该错误与您的

ContentType:'application/json',

应该是

contentType: 'application/json',

并删除此

dataType: "json"

jQuery.ajax尝试根据指定的dataType参数或服务器发送的Content-Type标头转换响应主体.如果转换失败(例如JSON/XML无效),则会触发错误回调.在此处了解更多信息:Ajax请求返回200 OK,但是会引发错误事件而不是成功

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

我有这个要工作:

EnterpriseController.cs

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

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

这篇关于无法将Post Data从Ajax发送到asp.net核心Web API?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆