集合在 ASP.NET WebApi 中返回 null

Collection is returning null in ASP.NET WebApi

我正在使用 ASP.NET WebApi 2.0 我已经在本地服务器上发布了它并正在尝试使用这些服务

这就是我的 Api 控制器的样子

public class TestController : ApiController
{
    public List<string> names = new List<string>();
    public String Get()
    {
        return "Hello I am Service";
    }

    public IEnumerable<string> Post([FromBody]string custName)
    {
        try
        {

            names.Add(custName);
            return names;
        }
        catch(Exception ex)
        {
            return null;
        }           
    }
}

我正在使用 jQuery AJAX 到 post 值,它看起来如下

var customerName = $('#txtName').val();

$.ajax(
{
 url:"http://myip:8060/Api/Test",
 method:"POST",
 data:{'custName',customerName},
 success:function(data)
 {
  console.log(data);
 }
error:function(e)
{
 console.log(e);
}
})

现在,如果我提醒 customerName,我会得到正确的值,但是当我返回时,控制器的 Post 操作返回 null,如下所示

[null]
[null,null] 

我的问题是为什么值会变成空值?

在 jQuery 试试这个:

var customerName = $('#txtName').val();

$.ajax(
{
 url:"http://myip:8060/Api/Test",
 method:"POST",
 data:JSON.stringify({'custName':customerName}),
 success:function(data)
 {
  console.log(data);
 }
error:function(e)
{
 console.log(e);
}
})

试试这个:-

    var customerName = $('#txtName').val();

      $.ajax(
     {
      url:"http://myip:8060/Api/Test", 
      method:"POST",
      data: { custName: customerName },
      success:function(data)
      {
       console.log(data);
      }
      error:function(e)
      {
       console.log(e);
      }
    })

嗯,控制器在尝试执行 post 请求时以某种方式出错。 在你的控制器中试试这个:

public List<string> Post()//[FromBody]string custName)
    {
        HttpContent requestContent = Request.Content;
        string custName = requestContent.ReadAsStringAsync().Result;

        try
        {

            names.Add(custName);
            return names;
        }
        catch (Exception ex)
        {
            List<string> errors = new List<string> {ex.Message};
            return errors;
        }



    }

我使用的html如下:

    <!DOCTYPE html>

<html>
<head>
    <title></title>
    <meta charset="utf-8"/>
</head>
<body>
First name: <input type="text" id="demo2" onkeyup="showitemresult()" ><br>
    result name: <input type="text" id="demo" ><br>
</body>
</html>
<script>
    function showitemresult() {
        var xhttp = new XMLHttpRequest();
        xhttp.onreadystatechange = function () {
            if (xhttp.readyState == 4 && xhttp.status == 200) {
                document.getElementById("demo").value = xhttp.responseText;
            }
        };
        xhttp.open("POST", "http://localhost:52016/api/values", true);
        xhttp.send(document.getElementById("demo2").value);
    }
</script>

http://localhost:52016/api/values更改为您的地址 编辑 2:我注意到 js 不是 jquery。但是我让它起作用了。

ASP.NET Web API 的模型绑定器无法将 JSON 转换为字符串,您必须使用对象来完成此操作。

所以你有 3 个选项来解决你的问题

首先,使用查询字符串

在您的操作中将属性 FromBody 更改为 FromUri,就像那样

public IEnumerable<string> Post([FromUri]string custName)
{
    try
    {
        names.Add(custName);
        return names;
    }
    catch (Exception ex)
    {
        return null;
    }
}

然后更改您的 javascript 代码

$.post("/Api/Test/?custName=" + customerName, function(data) {
    console.log(data);
}).error(function(e) {
    console.log(e);
});

二、使用路由属性

用这样的 Route 属性装饰你的动作

[Route("api/test/{custName}")]
public IEnumerable<string> Post([FromUri]string custName)
{
    try
    {
        names.Add(custName);
        return names;
    }
    catch (Exception ex)
    {
        return null;
    }
}

然后更改您的 javascript 代码

$.post("/Api/Test/" + customerName, function(data) {
    console.log(data);
}).error(function(e) {
    console.log(e);
});    

Obs.: 要使用 Route 属性,您必须在 WebApiConfig 中对其进行配置,因此您必须在此处设置此行:

config.MapHttpAttributeRoutes();

所以你的WebApiConfig应该是这样的

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services

        // Web API routes
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}

三、使用视图模型class

创建一个class

public class ViewModel
{
    public string custName { get; set; }
}

使用 FromBody 属性在您的操作中接收此模型

public IEnumerable<string> Post([FromBody]ViewModel viewModel)
{
    try
    {
        names.Add(viewModel.custName);
        return names;
    }
    catch (Exception ex)
    {
        return null;
    }
}

然后更改您的 javascript 代码

$.post("/Api/Test/", { custName: customerName }, function(data) {
    console.log(data);
}).error(function(e) {
    console.log(e);
});

观察:您的控制器有一个小错误

public class TestController : ApiController
{
    public List<string> names = new List<string>();

    public string Get()
    {
        return "Hello I am Service";
    }

    //Rest of code
}

Web API 和 MVC 中的每个控制器每次在服务器处理请求时都会创建,因此您在 TestController class 中的 names 字段将在每个请求中成为一个新的列表,如果你想在这个列表中的其他请求中保留数据,请将其设置为静态

public static List<string> names = new List<string>();