Web API复杂参数属性全为空 [英] Web API complex parameter properties are all null

查看:75
本文介绍了Web API复杂参数属性全为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Web API服务调用,可以更新用户的首选项.不幸的是,当我从jQuery ajax调用中调用此POST方法时,请求参数对象的属性始终为null(或默认值),而不是传入的内容.如果我使用REST客户端调用相同的确切方法(我使用Postman) ,效果很好.我无法弄清楚我在做什么错,但希望有人以前见过.这很简单...

I have a Web API service call that updates a user's preferences. Unfortunately when I call this POST method from a jQuery ajax call, the request parameter object's properties are always null (or default values), rather than what is passed in. If I call the same exact method using a REST client (I use Postman), it works beautifully. I cannot figure out what I'm doing wrong with this but am hoping someone has seen this before. It's fairly straightforward...

这是我的请求对象:

public class PreferenceRequest
{
    [Required]
    public int UserId;

    public bool usePopups;
    public bool useTheme;
    public int recentCount;
    public string[] detailsSections;
}

这是UserController类中的我的控制器方法:

Here's my controller method in the UserController class:

    public HttpResponseMessage Post([FromBody]PreferenceRequest request)
    {
        if (request.systemsUserId > 0)
        {
            TheRepository.UpdateUserPreferences(request.UserId, request.usePopups, request.useTheme,
                                         request.recentCount, request.detailsSections);

            return Request.CreateResponse(HttpStatusCode.OK, "Preferences Updated");                
        }
        else
        {
            return Request.CreateErrorResponse(HttpStatusCode.NotAcceptable, "You must provide User ID");
        }
    }

这是我的ajax电话:

Here's my ajax call:

var request = {
    UserId: userId,
    usePopups: usePopups,
    useTheme: useTheme,
    recentCount: recentCount,
    detailsSections: details
};

$.ajax({
    type: "POST",
    data: request,
    url: "http://localhost:1111/service/User",
    success: function (data) {
        return callback(data);
    },
    error: function (error, statusText) {
        return callback(error);
    }
});

我尝试设置dataType& contentType用于几种不同的事物('json','application/json'等),但是请求对象的属性始终为默认值或为null.因此,例如,如果我传入此对象:

I've tried setting the dataType & contentType to several different things ('json', 'application/json', etc) but the properties of the request object are always defaulted or null. So, for example, if I pass in this object:

var request = {
  UserId: 58576,
  usePopups: false,
  useTheme: true,
  recentCount: 10,
  detailsSections: ['addresses', 'aliases', 'arrests', 'events', 'classifications', 'custody', 'identifiers', 'phone', 'remarks', 'watches']
}

我可以看到一个完全填充的请求对象,带有上面列出的有效值.但是在Web API控制器中,请求在那里,但是属性如下:

I can see a fully populated request object with the valid values as listed above. But in the Web API controller, the request is there, but the properties are as follows:

  UserId: 0,
  usePopups: false,
  useTheme: false,
  recentCount: 0,
  detailsSections: null

仅供参考-我不会在此项目中使用任何ASP.Net MVC或ASP.NET页面,只是使用Web API作为服务,并使用jQuery $ .ajax进行所有调用.

FYI - I'm not doing ANY ASP.Net MVC or ASP.NET pages with this project, just using the Web API as a service and making all calls using jQuery $.ajax.

知道我在做什么错吗?谢谢!

Any idea what I'm doing wrong here? Thanks!

更新:我只想指出,在同一控制器的同一Web API项目中,我有很多方法可以做到完全相同,因此我称完全相同,它们可以完美地工作!我已经花了一个上午比较各种调用,并且方法或标头似乎没有任何区别,但是在这种特定方法上却行不通.

UPDATE: I just want to note that I have many methods in this same Web API project in other controllers that do this exact same thing, and I am calling the exact same way, and they work flawlessly! I have spent the morning comparing the various calls, and there doesn't appear to be any difference in the method or the headers, and yet it just doesn't work on this particular method.

我也尝试过切换到Put方法,但得到的结果完全相同-进入了请求对象,但未填充正确的值.令人沮丧的是,我在这个项目中有大约20个控制器类,而Posts可以在所有这些类中工作...

I've also tried switching to a Put method, but I get the exact same results - the request object comes in, but is not populated with the correct values. What's so frustrating is that I have about 20 controller classes in this project, and the Posts work in all of those...

推荐答案

对于Asp.Net WebAPI,这似乎是一个常见问题.
通常,空对象的原因是将json对象反序列化为C#对象.不幸的是,调试非常困难-因此很难找到问题所在.
我更喜欢只将完整的json作为对象发送,然后手动反序列化.至少这样,您会得到真正的错误,而不是空值.
如果将方法签名更改为接受对象,请使用JsonConvert:

This seems to be a common issue in regards to Asp.Net WebAPI.
Generally the cause of null objects is the deserialization of the json object into the C# object. Unfortunately, it is very difficult to debug - and hence find where your issue is.
I prefer just to send the full json as an object, and then deserialize manually. At least this way you get real errors instead of nulls.
If you change your method signature to accept an object, then use JsonConvert:

public HttpResponseMessage Post(Object model)
        {
            var jsonString = model.ToString();
            PreferenceRequest result = JsonConvert.DeserializeObject<PreferenceRequest>(jsonString);
        }

这篇关于Web API复杂参数属性全为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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