Web API 控制器操作参数始终为 null

本文关键字:null 参数 API 控制器 操作 Web | 更新日期: 2023-09-27 18:33:13

我确实在这里看到了一些解决类似问题的线程,但不幸的是,没有什么可以解决我的问题(到目前为止(。

控制器方法

以下是我的控制器方法:

[EnableCors("AllowAll")]
[RouteAttribute("SearchBooks")]
[HttpGet("searchbooks/{key}")]
public async Task<object> SearchBooks(string key)
{
    using (var cmd = _ctx.Database.GetDbConnection().CreateCommand())
    {
        cmd.CommandText = "SearchBooks";
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.Add(new SqlParameter("@Key", SqlDbType.NVarChar) { Value = key });
        if (cmd.Connection.State == ConnectionState.Closed)
            cmd.Connection.Open();
        var retObj = new List<dynamic>();
        using (var dataReader = await cmd.ExecuteReaderAsync())
        {
            while (await dataReader.ReadAsync())
            {
                //Namespace for ExpandoObject: System.dynamic
                var dataRow = new ExpandoObject() as IDictionary<string, object>;
                for (var iFiled = 0; iFiled < dataReader.FieldCount; iFiled++)
                    dataRow.Add(dataReader.GetName(iFiled), dataReader[iFiled]);
                retObj.Add((ExpandoObject)dataRow);
            }
        }
        if (!retObj.Any())
            return JsonConvert.SerializeObject("No matching record found");
        else
            return JsonConvert.SerializeObject(retObj);
    }
}

当我检查控制台的输出时,它说

fail: Microsoft.AspNet.Server.Kestrel[13] 应用程序引发了未经处理的异常。System.Data.SqlClient.SqlException (0x80131904(:过程或函数"SearchBooks"需要参数"@Key",但未提供。

我在本地创建了另一个网站,专门用于测试CORS问题(工作正常(。我通过以下方式通过AJAX调用上述方法:

<script type='text/javascript'>
$.ajax({
  type: "POST",
  url: "http://localhost:5000/api/bookstore/SearchBooks",
  data: { 'key': 'van' },
  dataType: 'json',
  contentType:"application/json",
  success: function (res) {
    $("#response").html(res);
  },
  error: function (err) {
  }
});
</script>  

问题是控制器方法中参数key的值SearchBooks总是null

但是如果我创建一个model(下图(

public class SearchViewModel{
  public string SearchKey {get; set;}
}

然后,如果我修改我的AJAX以将值传递给此model,如下所示,一切正常!

<script type='text/javascript'>
  var searchModel={
    key: 'van'
  }
  $.ajax({
    type: "POST",
    data: JSON.stringify(searhModel),
    url: "http://localhost:5000/api/bookstore/searchbooks",
    contentType:"application/json",
    success: function (res) {
      $("#response").html(res);
    },
    error: function (err) {
    }
});
</script>

请帮忙!

Web API 控制器操作参数始终为 null

在 ajax 调用中使用 type: "GET"

您的网址应如下所示 url: "http://localhost:5000/api/bookstore/SearchBooks/van"最后删除data

最终代码:

  $.ajax({
  type: "GET",
  url: "http://localhost:5000/api/bookstore/SearchBooks/van",
  dataType: 'json',
  contentType:"application/json",
  success: function (res) {
    $("#response").html(res);
  },
  error: function (err) {
  }
});

当参数具有 [FromBody] 时,Web API 使用 Content-Type 标头来选择格式化程序。

public async Task<object> SearchBooks([FromBody]string key){
}

请参阅 Web API ASP.NET 参数绑定

根据您的

问题,您的 JSON 格式似乎无效,当您使用 Stringify 时,它会生成有效的 JSON,因此它可以正常工作。因此,请尝试从 ajax 调用中的"key"中删除 qout。例如

<script type='text/javascript'>
$.ajax({
  type: "POST",
  url: "http://localhost:5000/api/bookstore/SearchBooks",
  data: { key: 'van' },
  dataType: 'json',
  contentType:"application/json",
  success: function (res) {
    $("#response").html(res);
  },
  error: function (err) {
  }
});
</script>