【问题标题】:Can't send Post Data from Ajax to asp.net core web api?无法从 Ajax 将 Post 数据发送到 asp.net core web api?
【发布时间】:2019-12-13 15:56:17
【问题描述】:

我需要向我的 asp.net 核心 web 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 ,因此通常不会引发问题。 我也向该网络服务发出了成功的获取请求

【问题讨论】:

    标签: ajax asp.net-core-webapi


    【解决方案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");
        }
    }
    

    索引.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
    

    【讨论】:

    【解决方案2】:
    1. 从控制器中删除[FromBody]

    2.在控制器类下面使用这个[ApiController]

    3.用这个发帖

    $.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.把[IgnoreAntiforgeryToken]放在你的actionresult的顶部

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-11-19
      • 1970-01-01
      • 1970-01-01
      • 2022-06-14
      • 2017-11-26
      • 1970-01-01
      • 1970-01-01
      • 2021-10-12
      相关资源
      最近更新 更多