【问题标题】:My Asp.Net 5 web api service recieves Posted Json as NULL我的 Asp.Net 5 web api 服务收到 Posted Json 为 NULL
【发布时间】:2015-11-08 14:25:12
【问题描述】:

您好,因为我无法将 Json 数据发送到 Asp.Net 5 的 API 服务,所以我使用在 StackOverflow 中找到的这个方法:

var param = function (obj) {
        var query = '';
        var name, value, fullSubName, subName, subValue, innerObj, i;

        for (name in obj) {
            value = obj[name];

            if (value instanceof Array) {
                for (i = 0; i < value.length; ++i) {
                    subValue = value[i];
                    fullSubName = name + '[' + i + ']';
                    innerObj = {};
                    innerObj[fullSubName] = subValue;
                    query += param(innerObj) + '&';
                }
            }
            else if (value instanceof Object) {
                for (subName in value) {
                    subValue = value[subName];
                    fullSubName = name + '[' + subName + ']';
                    innerObj = {};
                    innerObj[fullSubName] = subValue;
                    query += param(innerObj) + '&';
                }
            }
            else if (value !== undefined && value !== null) {
                query += encodeURIComponent(name) + '=' + encodeURIComponent(value) + '&';
            }
        }
        return query.length ? query.substr(0, query.length - 1) : query;
    };

我设置:

'Content-Type': 'application/x-www-form-urlencoded'

但是当我发展到更复杂的模型时,这个参数方法无法转换数据模型,例如:

{ RoleStatuses: [{Role: "Admin", IsInRole: true}, {Role: "User", IsInRole: false}, ...], UserName: "MyUser" }

当我在 API 服务中收到此模型时,可以识别 UserName 但 Array count = 0,当我想将此数据作为 json 发送时,UserName 和 Array 都为空,我陷入了这种情况,无法更进一步,所以请帮忙。

【问题讨论】:

  • 首先,如果将 Json 传递给 api,则 Content-Type 标头需要为 application/json。您可以做的最好的事情是使用 Fiddler 来获取请求(标头和 POST 正文)并显示正在调用的 WebApi 控制器的方法,我们可以看到为什么模型绑定不适合您。
  • 您的出色帮助如何?

标签: c# asp.net json asp.net-web-api


【解决方案1】:

感谢互联网我找到了放置属性的答案:

[HttpPost]
    [Route("UpdateRoles")]
    public AdminAccountGenericResponse UpdateRoles([FromBody]RoleStatusUserModel model)
    {

[FromBody] 在 Model 参数前面。

【讨论】:

  • 您应该将其标记为“已接受的答案”,即使是您自己添加的 :)
【解决方案2】:

POST 是:

JSON

角色状态 [对象 { Role="Administrators", IsUserInRole=false, $$hashKey="object:53"}, Object { Role="Editors", IsUserInRole=false, $$hashKey="object:54"}, Object { 角色="Members", IsUserInRole=true, $$hashKey="object:55"}, Object { Role="Users", IsUserInRole=true, $$hashKey="object:56"}]

0 对象 { Role="Administrators", IsUserInRole=false, $$hashKey="object:53"}

$$hashKey “对象:53”

IsUserInRole 假的

角色 “管理员”

1 对象 { Role="Editors", IsUserInRole=false, $$hashKey="object:54"}

$$hashKey “对象:54”

IsUserInRole 假的

角色 “编辑”

2 对象 { Role="Members", IsUserInRole=true, $$hashKey="object:55"}

$$hashKey “对象:55”

IsUserInRole 真的

角色 “成员”

3 对象 { Role="Users", IsUserInRole=true, $$hashKey="object:56"}

$$hashKey “对象:56”

IsUserInRole 真的

角色 “用户”

用户名 “阿明”

来源 {"RoleStatuses":[{"Role":"Administrators","IsUserInRole":false,"$$hashKey":"object:53"},{"Role":"Editors" ,"IsUserInRole":false,"$$hashKey":"object:54"},{"Role":"Members","IsUserInRole":true,"$$hashKey":"object :55"},{"Role":"Users","IsUserInRole":true,"$$hashKey":"object:56"}],"UserName":"Armin"}

标题是:

查看源代码 缓存控制
私人的,最大年龄=0 内容长度
18964 内容类型
文本/html;字符集=utf-8 日期
格林威治标准时间 2015 年 11 月 8 日星期日 21:42:59 X-Powered-By
ASP.NET X-SourceFiles
=?UTF-8?B?QzpcVXNlcnNcbWF6aWFfMDAwXERlc2t0b3BcV2ViQW5ndWxhclxzcmNcV2ViQW5ndWxhclx3d3dyb290XGFwaVxBZG1pbkFjY291bnRcVXBkYXRlUm9sZXM =?= 查看源代码 接受
应用程序/json 接受编码 gzip,放气 接受语言 en-US,en;q=0.5 缓存控制
无缓存 连接
活着 内容长度
296 内容类型
应用程序/json;字符集=UTF-8 饼干
.ASPXANONYMOUS=BJm2d-pQ0QEkAAAANzQ1YWFkY2UtMTgyYi00NWE4LWI0ZTgtNjczZTcyZDY2Yzdi248xiSOVN90mD-0q5eEh6bMyxhZub9zJ7JIMsaU9BP81 ; WebAngularCookie=C029A9A2E3E114C01C2D8F3829B00D7C18FDB1740D16E006EF09F098BA056355BC782EED8BBF129FF 8AB546EED2758409BEB5B0D4AF0D5EDDF11C6BF6FDB84235DCA60E86EBF1D4B1B34449915E4ACCF6A31F11DF0B83AC1FF0F3 A0A5FE17209C1BE91E7A90BE720FBD1B88AE46D6DFA4B0F450E29725F63B65974F5E552F15FBD37BF7C017E9A4DD13ECD942 09EE99672255DB2961B30FE319E608897CD513F81CA350C90374AF22000DAF39A69A5F7 主机
本地主机:13661 编译指示
无缓存 推荐人 http://localhost:13661/Admin/ManageUser/?userName=Armin 请求验证令牌
CfDJ8LcZVsUv5KZJqpUyBqND_NYoqgSfNrV2Z1YEIuE6u2YSRdGF9Oec2SLkyfxmgIkOEBoQ9F2O7tm24jw-7_MXL-DGAbhQt-dcCYt0rY-hhBwHsA9w5Qf6ql4HegBAuHrkUCZbxgW8BTZkNlBuw4 :CfDJ8LcZVsUv5KZJqpUyBqND_NYE7Fd-vdtFHfxlHC2qLWHx2THGQuNbIhWLleaRBgC4SaQqkC1pEMP0yoi9p5QihhKxMpKe0da M3OE5Wg6S8ZHyLG2dZyrUJYmGVB_izi_yq2hb4VgDngQlCzx6Qv7Fo28 用户代理
Mozilla/5.0 (Windows NT 6.3; WOW64; rv:41.0) Gecko/20100101 Firefox/41.0

客户服务:

updateRoles: function (roleStatusUserModel, successSucceed, successFailed, error) {                
            $http({
                url: '/api/AdminAccount/UpdateRoles',
                method: "POST",
                data: JSON.stringify(roleStatusUserModel),
                headers: {
                    'Content-Type': 'application/json', 'Accept': 'application/json', 'RequestVerificationToken': $rootScope.RequestVerificationToken
                }
            })
               .success(function (data) {
                   if (data.Success == true) {
                       theMessage = data.Message;
                       theError = data.Error;
                       successSucceed();
                   }
                   else {
                       theMessage = data.Message;
                       theError = data.Error;
                       successFailed();
                   }
               }).error(function () {
                   error();
               });
        }

和 API 服务:

    [HttpPost]
    [Route("UpdateRoles")]
    public AdminAccountGenericResponse UpdateRoles(RoleStatusUserModel model)
    {

        ValidateRequestHeader(Request);

        if (!Authorize(Context, Request, new string[] { "Administrators" }))
            throw new ApplicationException("Not Authorized");

        var roles = Roles.GetAllRoles();
        //MembershipUser user = Membership.GetUser(model.UserName);

        foreach (string role in roles)
        {
            RoleStatus roleStat = model.RoleStatuses.FirstOrDefault(rs => rs.Role == role);

            if (roleStat != null)
            {
                if (roleStat.IsUserInRole == true && !Roles.IsUserInRole(model.UserName, role))
                {
                    Roles.AddUserToRole(model.UserName, role);
                }
                else if (roleStat.IsUserInRole == false && Roles.IsUserInRole(model.UserName, role))
                {
                    Roles.RemoveUserFromRole(model.UserName, role);
                }
                else
                { }
            }
            else
            {
                return new AdminAccountGenericResponse
                {
                    Success = false,
                    Message = "",
                    Error = "Role is null."
                };
            }
        }

        return new AdminAccountGenericResponse
        {
            Success = true,
            Message = "Roles Updated",
            Error = ""
        };
    }

还有模特:

public class RoleStatus
{
    public string Role { get; set; }
    public bool IsUserInRole { get; set; }
}

public class RoleStatusUserModel
{
    public List<RoleStatus> RoleStatuses { get; set; }
    public string UserName { get; set; }
}

【讨论】:

  • 我不认为这是 ASP.NET 5,是吗?
  • 是 Asp.Net 5 服务 + Angularjs 客户端。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-24
  • 2013-08-10
  • 1970-01-01
  • 1970-01-01
  • 2012-03-10
  • 2019-09-02
相关资源
最近更新 更多