C# 集合在ASP.NET WebApi中返回null

C# 集合在ASP.NET WebApi中返回null,c#,jquery,asp.net,asp.net-mvc,asp.net-web-api,C#,Jquery,Asp.net,Asp.net Mvc,Asp.net Web Api,我正在使用ASP.NET WebApi 2.0,我已经在localserver上发布了它,并且正在尝试使用这些服务 这就是我的Api控制器的外观 public class TestController : ApiController { public List<string> names = new List<string>(); public String Get() { return "Hello I am Service";

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

这就是我的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;
        }           
    }
}
现在,如果我提醒customerName,我得到的是正确的值,但是当我返回时,控制器的Post操作返回null,如下所示

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



    }
public List Post()//[FromBody]字符串custName)
{
HttpContent requestContent=Request.Content;
字符串custName=requestContent.ReadAsStringAsync().Result;
尝试
{
名称。添加(客户名称);
返回姓名;
}
捕获(例外情况除外)
{
列表错误=新列表{ex.Message};
返回错误;
}
}
我使用的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>

名字:
结果名称:
函数showitemresult(){ var xhttp=newXMLHttpRequest(); xhttp.onreadystatechange=函数(){ 如果(xhttp.readyState==4&&xhttp.status==200){ document.getElementById(“demo”).value=xhttp.responseText; } }; xhttp.open(“POST”http://localhost:52016/api/values“,对); xhttp.send(document.getElementById(“demo2”).value); }
改你的地址
编辑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;
    }
}
[Route("api/test/{custName}")]
public IEnumerable<string> Post([FromUri]string custName)
{
    try
    {
        names.Add(custName);
        return names;
    }
    catch (Exception ex)
    {
        return null;
    }
}
其次,使用路由属性 用这样的路线属性装饰你的行动

public IEnumerable<string> Post([FromUri]string custName)
{
    try
    {
        names.Add(custName);
        return names;
    }
    catch (Exception ex)
    {
        return null;
    }
}
[Route("api/test/{custName}")]
public IEnumerable<string> Post([FromUri]string custName)
{
    try
    {
        names.Add(custName);
        return names;
    }
    catch (Exception ex)
    {
        return null;
    }
}
Obs.:要使用
路由
属性,您必须在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 }
        );
    }
}
第三,使用视图模型类 创建一个类

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;
    }
}
注意:您的控制器有一个小错误
公共类TestController:ApiController
{
公共列表名称=新列表();
公共字符串Get()
{
返回“你好,我是服务”;
}
//代码的其余部分
}
Web API和MVC中的每个控制器都是在服务器每次处理请求时创建的,因此TestController类中的名称字段将是每个请求中的一个新列表,如果您希望将此列表中的数据保留在其他请求中,请将此设置为静态

public static List<string> names = new List<string>();
公共静态列表名称=新列表();

如果您的意思是在传递custName时我应该删除quote,那么我检查了它,但没有任何区别<代码>数据:{custName:customerName}或
数据:{'custName':customerName}
我已经提供了所有需要的操作&jQuery ajax callChecked,但仍然返回nullchecked,但不是返回null,而是返回为
[“”]
[“”,”“]
否,onkeyUp事件我在操作不受支持的媒体类型(405)上出错。嗯,您是否也复制了控制器?我这里有密码。你的地址会像我回答的那样,看@Alberto.。我应该对你说些什么,伙计。再一次真诚的感谢。。。高-5@Alerto..only有一件事需要检查它有什么区别&如何从查询字符串的URL中获取数据,如下
www.youtube.com/?w=videocode
FromBody
尝试从服务器中收到的HTTP请求的正文中获取数据。这是我几周前提出的一个问题,但没有得到正确的ans,请您看一看,好吗?请看一下,我有点急着要这个要求。
$.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
}
public static List<string> names = new List<string>();