收集在ASP.NET的WebAPI返回null [英] Collection is returning null in ASP.NET WebApi

查看:107
本文介绍了收集在ASP.NET的WebAPI返回null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用ASP.NET的WebAPI 2.0我已经出版了它的LocalServer,我试图消费服务

I am using ASP.NET WebApi 2.0 I have published it on localserver and am trying to consume the services

这是我的API控制器的外观

This is how my Api Controller looks

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发布的价值观和放大器;它看起来如下

I am using jQuery AJAX to post the values & it looks as below

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

现在,如果我提醒客户名称,我得到了正确的价值,但是当我返回控制器的动作后正在返回空,如下

Now if I alert customerName, I am getting the correct value, but when I am returning the Post action of the controller is returning null as below

[null]
[null,null] 

我的问题是,为什么值越来越空?

推荐答案

的ASP.NET Web API的模型绑定无法转换一个JSON为一个字符串,则必须使用对象要做到这一点想法。

The model binder of ASP.NET Web API can't translate a JSON to a string, you must use an object to do this think.

所以,你有3种选择来解决您的问题。

So you have 3 options to fix your problem

在你的行动改变属性 FromBody FromUri ,像

In your action change the attribute FromBody to FromUri, like that

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

然后改变你的JavaScript code

Then change your javascript code

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

二,使用路由属性

与装饰您的路线action属性一样,

Second, use route attribute

Decorate your action with Route attribute like that

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

然后改变你的JavaScript code

Then change your javascript code

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

观测值::要使用路线属性您必须WebApiConfig配置它,所以你必须有这行有:

Obs.: To use the Route attribute you must configure it in WebApiConfig, so you must have this line there:

config.MapHttpAttributeRoutes();

所以,你WebApiConfig应该是这样的。

So your WebApiConfig should be like this

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属性

Receive this model in your action, using FromBody attribute

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

然后改变你的JavaScript code

Then change your javascript code

$.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
}

在网页API和MVC创建每次当一个请求是由服务器处理的每个控制器,因此您的名称中的TestController类字段将在每一个请求一个新的列表,如果你想保持在此列表中其他请求的数据,使这个静态

Each controller in Web API and MVC is created everytime when a request is handled by the server, so your names field in TestController class will be a new List in every request, if you want to keep data in this list other requests, make this static

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

这篇关于收集在ASP.NET的WebAPI返回null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆