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

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

问题描述

我有一个更新用户首选项的 Web API 服务调用.不幸的是,当我从 jQuery ajax 调用中调用此 POST 方法时,请求参数对象的属性始终为空(或默认值),而不是传入的内容.如果我使用 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天全站免登陆