WebAPI 2 [FromBody]参数未设置 [英] WebAPI 2 [FromBody] parameter not getting set

查看:80
本文介绍了WebAPI 2 [FromBody]参数未设置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非常基本的情况……我觉得我已经做过100次了,但是由于某种原因,它决定不工作,把我的时间浪费在一些琐碎的事情上……

I have what should be a VERY basic scenario ... one which I feel I have done 100 time before but for some reason it has decided to NOT work and waste my time on something trivial ...

我正在使用带有属性路由的WebAPI(喜欢它们).

I am using WebAPI with Attribute routes (love them).

我正在尝试传递两个参数,一个是来自Body的参数,另一个是来自Uri的参数.它们都是基本类型,一种是 Boolean ,另一种是 Long SponsorID.

I am trying to pass in two parameters, one from the Body and one from the Uri. They are both basic types ... one a Boolean and the other a Long sponsorID.

非常简单的服务签名...

Pretty simple service signature ...

[HttpPut]
[Route("adminAPI/sponsors/{sponsorID:long}/Enable")]
public HttpResponseMessage EnableSponsor([FromBody]Boolean enabled, [FromUri] Int64 sponsorID)
{
    HttpResponseMessage ret = null;
    // does stuff and populates the response
    return ret;
}

使用Postman和Advanced REST Client和JQuery/Chrome,我收到了错误请求"错误...

Using Postman and Advanced REST Client and JQuery/Chrome I have been getting "Bad Request" errors ...

var request = function () {

    $.ajax({
        type: 'PUT',
        url: 'http://localhost:50865/adminAPI/Sponsor/23/Enable',
        data: { "enabled": true },
        contentType: "application/json"
    })
    .done(function (data, textStatus, jqXHR) {

        if ([200, 204, 304].indexOf(data.StatusCode) === -1) {

        } else {

        }
    })
    .fail(function (jqXHR, textStatus, errorThrown) {
    });
};

我遇到以下错误...

I am getting the following error ...

参数字典包含参数的空条目方法的非空类型"System.Boolean"的"enabled"'System.Net.Http.HttpResponseMessage EnableSponsorBanner(Boolean,Int64)"位于"WEB.Admin.api.SponsorAPIController"中.可选参数必须为引用类型,可为null的类型,或声明为可选参数."

The parameters dictionary contains a null entry for parameter 'enabled' of non-nullable type 'System.Boolean' for method 'System.Net.Http.HttpResponseMessage EnableSponsorBanner(Boolean, Int64)' in 'WEB.Admin.api.SponsorAPIController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter."

由于某些原因,[FromBody]参数未与请求一起传递,从而导致错误.当我将参数设置为可为空时,请求会通过,但是,按预期方式,启用的参数为NULL?

For some reason the [FromBody] parameter is not being passed along with the request, resulting in the error. When I make the parameter nullable the request goes through but, as expected the enabled argument is NULL?

我在墙上撞头……有什么想法吗?

I am beating my head against the wall ... any ideas?

解决方案

我尝试仅从Web Service调用中删除密钥,但没有成功.相反,我创建了具有基本数据类型的数据传输对象(DTO),这些数据类型可能会单独发送给服务.我可以使用它来传递此模型,以便为此和将来提出的任何其他请求传递简单的值引用.

I tried simply removing the key from the Web Service call and had no success. Instead I created a Data Transfer Object (DTO) with the basic datatypes that I might send to a service individually. I can use this to pass this model to pass simple value references for this and any other requests made in the future.

//
// The Data Transfer Object
    public class APIValueTypes
    {
        public Boolean booleanValue { get; set; }

        public Int64 longValue { get; set; }

        public String stringValue { get; set; }

        public DateTime dateValue { get; set; }
    }

由于该服务知道它所寻找的价值,因此可以获取所需的任何价值.

Since the Service knows what value it's looking for it can grab whatever value it requires.

[HttpPut]
[Route("adminAPI/sponsors/{sponsorID:long}/Enable")]
public HttpResponseMessage EnableSponsor([FromBody]APIValueTypes enabled, [FromUri] Int64 sponsorID)
{
    HttpResponseMessage ret = null;
    Boolean isEnabled = enabled.booleanValue;
    // does stuff and populates the response
    return ret;
}

CAVEAT

这时我不得不承认,尽管我在REST工具中使用了它,但仍无法在JQuery实现中使用它.因此,尽管我的帖子得到了答复,但我仍然遇到JQuery ajax $的另一个问题...即使我在DTO对象中发送,服务方法仍会收到null而不是对象...(我怀疑是另一篇帖子...-叹气)

I have to confess at this time however that while I have it working in my REST tools, I have been unable to get it to work in my JQuery implementation. So while my post has been answered I am having another issue with JQuery ajax$ ... Even though I am sending in the DTO object the service method still receives a null instead of the object ... (another post I suspect ... - sigh)

var request = function () {

    $.ajax({
        type: 'PUT',
        url: 'http://localhost/adminAPI/Sponsor/23/Enable',
        data: { "booleanValue": false },
        contentType: "application/json",

    })
    .done(function (data, textStatus, jqXHR) {

        console.log(data);

        if ([200, 204, 304].indexOf(data.StatusCode) === -1) {

        } else {

        }
    })
    .fail(function (jqXHR, textStatus, errorThrown) {
    });
};

CAVEAT解决方案

我发现仅发送JSON对象作为数据有效负载是行不通的.我必须对数据进行字符串化"才能将其序列化回APIValueTypes参数数据类型.因此,从JQuery调用服务的过程现在看起来像...注意 data 分配...

I discovered that simply sending the JSON object as the data payload was not working. I had to "stringify" the data in order to get it to be serialized back to the APIValueTypes parameter datatype. So the call to the service from JQuery now looks like ... pay attention to the data assignment ...

var request = function () {

    $.ajax({
        type: 'PUT',
        url: 'http://localhost/adminAPI/Sponsor/23/Enable',
        data: JSON.stringify({ "booleanValue": false }),
        contentType: "application/json",

    })
    .done(function (data, textStatus, jqXHR) {

        console.log(data);

        if ([200, 204, 304].indexOf(data.StatusCode) === -1) {

        } else {

        }
    })
    .fail(function (jqXHR, textStatus, errorThrown) {
    });
};

我希望有人能发现这个小小的旅程是有用的,并且当我在6个月内忘记它时,这篇博文仍然会在这里提醒我!!再次感谢!

I hope that someone can find this little journey useful and that when I forget it in 6 months this post will still be here to remind me as well!! Thanks again!

推荐答案

您遇到了此问题,因为您没有以ASP.Net Web API期望的格式发送数据.在处理诸如字符串和值类型(int,bool等)参数之类的值时,ASP.net Web API需要某些特殊格式,这些参数都用 FromBody 属性标记.

You have this issue because you are not sending the data in the format at which ASP.Net Web API expect. ASP.net Web API need some special format when dealing value like string and value type (int, bool etc) parameter are marked with FromBody attribute.

您的ASP.Net Web API期望使用原始类型,但是您要发送对象 {enabled:true} ,那么它将不会将其绑定到您的 enabled 参数不是对象.

Your ASP.Net Web API expect a primtiive type but you are sending an object { enabled: true } then it will not bind it to your enabled parameter which is not an object.

要使其正常工作,您必须使用以下代码作为jQuery ajax请求中的数据:

To make it work you must use the below code as data in your jQuery ajax request:

data: { "": true }

请注意,属性名称为空,这将告诉jQuery以 = true 格式发送数据.通过这种格式,ASP.Net Web API可以将其绑定到您的布尔参数.

Notice that the property name is empty that will tell jQuery to send the data in this format =true. With that format, ASP.Net Web API can bind it to your boolean parameter.

为防止该问题,请始终使用ViewModel.

To prevent that issue always use a ViewModel.

这篇关于WebAPI 2 [FromBody]参数未设置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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