简体   繁体   中英

My Asp.Net 5 web api service recieves Posted Json as NULL

Hello since I can't send Json data to Asp.Net 5's API Services I use this Method That I found in 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;
    };

And I set:

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

But when I progressed to more complex models, This param method can't convert a data model like:

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

And when I receive this model in API Service, UserName is recognized but Array count = 0, When I want to send this data as json both UserName and the Array are null, I stuck in this situation and cannot go further, so please help.

Thanks to the Internet I found My answer to place the attribute:

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

[FromBody] in front of the Model parameter.

POST is:

JSON

RoleStatuses [Object { Role="Administrators", IsUserInRole=false, $$hashKey="object:53"}, Object { Role="Editors", IsUserInRole=false, $$hashKey="object:54"}, Object { Role="Members", IsUserInRole=true, $$hashKey="object:55"}, Object { Role="Users", IsUserInRole=true, $$hashKey="object:56"}]

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

$$hashKey "object:53"

IsUserInRole false

Role "Administrators"

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

$$hashKey "object:54"

IsUserInRole false

Role "Editors"

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

$$hashKey "object:55"

IsUserInRole true

Role "Members"

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

$$hashKey "object:56"

IsUserInRole true

Role "Users"

UserName "Armin"

Source {"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"}

And Headers Are:

view source Cache-Control
private, max-age=0 Content-Length
18964 Content-Type
text/html; charset=utf-8 Date
Sun, 08 Nov 2015 21:42:59 GMT X-Powered-By
ASP.NET X-SourceFiles
=?UTF-8?B?QzpcVXNlcnNcbWF6aWFfMDAwXERlc2t0b3BcV2ViQW5ndWxhclxzcmNcV2ViQW5ndWxhclx3d3dyb290XGFwaVxBZG1pbkFjY291bnRcVXBkYXRlUm9sZXM =?= view source Accept
application/json Accept-Encoding gzip, deflate Accept-Language en-US,en;q=0.5 Cache-Control
no-cache Connection
keep-alive Content-Length
296 Content-Type
application/json; charset=UTF-8 Cookie
.ASPXANONYMOUS=BJm2d-pQ0QEkAAAANzQ1YWFkY2UtMTgyYi00NWE4LWI0ZTgtNjczZTcyZDY2Yzdi248xiSOVN90mD-0q5eEh6bMyxhZub9zJ7JIMsaU9BP81 ; WebAngularCookie=C029A9A2E3E114C01C2D8F3829B00D7C18FDB1740D16E006EF09F098BA056355BC782EED8BBF129FF 8AB546EED2758409BEB5B0D4AF0D5EDDF11C6BF6FDB84235DCA60E86EBF1D4B1B34449915E4ACCF6A31F11DF0B83AC1FF0F3 A0A5FE17209C1BE91E7A90BE720FBD1B88AE46D6DFA4B0F450E29725F63B65974F5E552F15FBD37BF7C017E9A4DD13ECD942 09EE99672255DB2961B30FE319E608897CD513F81CA350C90374AF22000DAF39A69A5F7 Host
localhost:13661 Pragma
no-cache Referer http://localhost:13661/Admin/ManageUser/?userName=Armin RequestVerificationToken
CfDJ8LcZVsUv5KZJqpUyBqND_NYoqgSfNrV2Z1YEIuE6u2YSRdGF9Oec2SLkyfxmgIkOEBoQ9F2O7tm24jw-7_MXL-DGAbhQt-dcCYt0rY-hhBwHsA9w5Qf6ql4HegBAuHrkUCZbxgW8BTZkNlBuwlZOJ4c :CfDJ8LcZVsUv5KZJqpUyBqND_NYE7Fd-vdtFHfxlHC2qLWHx2THGQuNbIhWLleaRBgC4SaQqkC1pEMP0yoi9p5QihhKxMpKe0da M3OE5Wg6S8ZHyLG2dZyrUJYmGVB_izi_yq2hb4VgDngQlCzx6Qv7Fo28 User-Agent
Mozilla/5.0 (Windows NT 6.3; WOW64; rv:41.0) Gecko/20100101 Firefox/41.0

Client Service:

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

And Api service:

    [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 = ""
        };
    }

And the models:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM