【问题标题】:asp.net webapi 2 post parameter values always null(string) or 0(int)asp.net webapi 2 post 参数值始终为 null(string) 或 0(int)
【发布时间】:2020-11-24 10:59:47
【问题描述】:

浏览了几十个链接,这些链接都说相同的解决方案。 为 api 调用中的参数创建一个对象。并使用 json 传递完全相同的对象。

因此 API 调用(被命中):

[System.Web.Http.HttpPost]
public Microsoft.AspNetCore.Mvc.JsonResult SearchItems([FromBody]SearchParams searchParams)

输入对象是这样定义的:

public class SearchParams
  {
    public string searchWord { get; set; }

    public int anid { get; set; }
  }

调用如下:

let item = {
          searchWord: searchKeyword.value.trim(),
          anid: 1
      };

      const uri = "../../WebApi/SearchItems";

      fetch(uri, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Accept': 'application/json'
        },
        body: JSON.stringify(item),
        //credentials: 'include',
        mode: 'cors',
      })

查看网络流量,传递的标头是这样的:

:authority: localhost:44386
:method: POST
:path: /WebApi/SearchItems
:scheme: https
accept: application/json
accept-encoding: gzip, deflate, br
accept-language: en-GB,en-US;q=0.9,en;q=0.8
content-length: 32
content-type: application/json
cookie: .AspNetCore.Session=CfDJ8LGmdU3gpbZIvSkveH0x8cMT8VibUQlc07yQ8SJOo6DJkNqykRsAz2V6NVuQ5zQhzBNiHjZ2iRJc%2Fno44sQdQJhsVPnktzx8EWu%2Bptg9ONjmErDP3TZ1csme%2FAJ3H5hSgvooxH0snE00och2ov4ZldFCosHYGH6X70ESjL8PbcJg; .AspNetCore.Antiforgery.Q2hy0CiNRlg=CfDJ8LGmdU3gpbZIvSkveH0x8cOOBFRZOyah2508xPXIUjTbV_weFLdM06pME-M-kc2l48FOmSym_5JS9GUHJeciQEKJI9SHBu1D-5wLcVF4de3rYsjKRsI67qGrCado7eBFDBAbeYFOLWEMbXXCQr_0vlA
origin: https://localhost:44386
referer: https://localhost:44386/lb_users/Details/11
sec-fetch-dest: empty
sec-fetch-mode: cors
sec-fetch-site: same-origin
user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36

因此有效载荷是:

{"searchWord":"qwerty","anid":1}

我的 VS 调试器和 Postman 都返回 null/0 值。

.net 核心相对较新。 那么我在这里缺少什么基本的东西,因为我看过的几十个 SO 问题似乎与我添加到我的解决方案中的内容相同?

提前致谢。

编辑: 这行得通。

const uri = "../../WebApi/SearchItems";
      fetch(uri, {
        method: 'POST',
        headers: {
          "Content-type": "application/x-www-form-urlencoded; charset=UTF-8"
        },
        body: "searchWord=" + searchKeyword.value.trim() + "&anid=1",
        //credentials: 'include',
        mode: 'cors',
      })

所以看起来 JSON 是问题所在。 JSON 对象是否已从传递给 api 调用中删除?

【问题讨论】:

    标签: .net-core fetch asp.net-core-webapi


    【解决方案1】:

    我测试了 asp .net webapi2 和 asp .net core,两者都可以工作。 下面是asp .net webapi2的demo:

    ApiController:

    public class ValuesController : ApiController
        {
            [System.Web.Http.HttpPost]
            public string GetVal(SearchParams searchParams)
            {
                return "success";
            }
        }
        public class SearchParams
        {
            public string searchWord { get; set; }
    
            public int anid { get; set; }
        }
    

    ajax:

    <input id="searchWord"/>
    <button onclick="sendData()">ssss</button>
    <script>
        function sendData() {
            let item = {
                searchWord: $("#searchWord").val().trim(),
                anid: 1
            };
    
            const uri = "../api/Values";
    
            fetch(uri, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Accept': 'application/json'
                },
                body: JSON.stringify(item),
                //credentials: 'include',
                mode: 'cors',
            })
        }
    </script>
    

    标题:

    :authority: localhost:44383
    :method: POST
    :path: /api/Values
    :scheme: https
    accept: application/json
    accept-encoding: gzip, deflate, br
    accept-language: en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7
    content-length: 33
    content-type: application/json
    cookie: .AspNetCore.Culture=c%3Den-US%7Cuic%3Den-US; .AspNetCore.Antiforgery.I5tvYLHG_pU=CfDJ8AkZmG9N6OhEnYVb3Xy31rQgFnXqHPkWTaV4nUodZGM9SfyhvD5jztl-kzo768oHkGPUYV-bOoSNBP5OuTHO_yd08w-IxrsO39HceHJgOIqC5ePYLIxXd0w9cBzYeWEu5amihQhOqiLySw376bp9YdM
    origin: https://localhost:44383
    referer: https://localhost:44383/Home/Index1
    sec-fetch-dest: empty
    sec-fetch-mode: cors
    sec-fetch-site: same-origin
    user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.66 Safari/537.36
    

    有效负载:

    {searchWord: "hghgfgf", anid: 1}
    

    结果: 您也可以尝试创建一个新项目并进行测试。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-02-07
      • 1970-01-01
      • 2020-05-22
      • 2019-09-30
      • 1970-01-01
      • 1970-01-01
      • 2021-01-26
      • 1970-01-01
      相关资源
      最近更新 更多