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

时间:2016-02-03 14:08:49

标签: javascript c# ajax asp.net-core asp.net-web-api2

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

控制器方法

以下是我的控制器方法:

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

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

  

失败:Microsoft.AspNet.Server.Kestrel [13]   应用程序抛出了未处理的异常。 System.Data.SqlClient.SqlException(0x80131904):过程或函数&#39; SearchBooks&#39;需要参数&#39; @ Key&#39;,这是未提供的。

我在本地创建了另一个网站,专门用于测试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(下面)

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>

请帮忙!

3 个答案:

答案 0 :(得分:1)

在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) {

  }
});

答案 1 :(得分:0)

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

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

}

请参阅Parameter Binding in ASP.NET Web API

答案 2 :(得分:0)

根据你的问题,似乎你的json格式无效,当你使用stringify时它生成有效的json,因此它工作正常。因此,请尝试从&#39;键&#39;中删除qouts。在你的ajax电话中。 e.g。

<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>
相关问题