您好,因为我无法将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'
但是当我进展到更复杂的模型时,这种param方法无法转换数据模型,如:
{ RoleStatuses: [{Role: "Admin", IsInRole: true}, {Role: "User", IsInRole: false}, ...], UserName: "MyUser" }
当我在API服务中收到此模型时,UserName被识别但是Array count = 0,当我想将此数据作为json发送时,UserName和Array都为null,我陷入了这种情况并且无法继续下去,所以请帮忙。
答案 0 :(得分:1)
感谢互联网,我发现我的答案是放置属性:
[HttpPost]
[Route("UpdateRoles")]
public AdminAccountGenericResponse UpdateRoles([FromBody]RoleStatusUserModel model)
{
Model参数前面的[FromBody] 。
答案 1 :(得分:0)
POST是:
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 对象{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”:[{ “角色”: “管理员”, “的isUserInRole”:假, “$$ hashKey”: “对象:53”},{ “角色”: “编辑” “的isUserInRole”:假, “$$ hashKey”: “对象:54”},{ “角色”: “成员”, “的isUserInRole”:真, “$$ hashKey”:“对象 :55 “},{” 角色 “:” 用户”, “的isUserInRole”:真, “$$ hashKey”: “对象:56”}], “用户名”: “阿明”}
和标题是:
查看来源
缓存控制
private,max-age = 0
内容长度
18964
内容类型
为text / html;字符集= utf-8的
日期
太阳,2015年11月8日21:42:59 GMT
X供电,通过
ASP.NET
X-SourceFiles
=?UTF-8 2 B 4 QzpcVXNlcnNcbWF6aWFfMDAwXERlc2t0b3BcV2ViQW5ndWxhclxzcmNcV2ViQW5ndWxhclx3d3dyb290XGFwaVxBZG1pbkFjY291bnRcVXBkYXRlUm9sZXM
=?=
查看源
接受
应用程序/ JSON
接受编码
gzip,deflate
接受语言
的en-US,连接; Q = 0.5
缓存控制
无缓存
连接
活着
内容长度
296
内容类型
应用/ JSON;字符集= UTF-8
饼干
.ASPXANONYMOUS = BJm2d-pQ0QEkAAAANzQ1YWFkY2UtMTgyYi00NWE4LWI0ZTgtNjczZTcyZDY2Yzdi248xiSOVN90mD-0q5eEh6bMyxhZub9zJ7JIMsaU9BP81
; WebAngularCookie = C029A9A2E3E114C01C2D8F3829B00D7C18FDB1740D16E006EF09F098BA056355BC782EED8BBF129FF
8AB546EED2758409BEB5B0D4AF0D5EDDF11C6BF6FDB84235DCA60E86EBF1D4B1B34449915E4ACCF6A31F11DF0B83AC1FF0F3
A0A5FE17209C1BE91E7A90BE720FBD1B88AE46D6DFA4B0F450E29725F63B65974F5E552F15FBD37BF7C017E9A4DD13ECD942
09EE99672255DB2961B30FE319E608897CD513F81CA350C90374AF22000DAF39A69A5F7
主机
本地主机:13661
附注
无缓存
引荐
http://localhost:13661/Admin/ManageUser/?userName=Armin
RequestVerificationToken
CfDJ8LcZVsUv5KZJqpUyBqND_NYoqgSfNrV2Z1YEIuE6u2YSRdGF9Oec2SLkyfxmgIkOEBoQ9F2O7tm24jw-7_MXL-DGAbhQt-dcCYt0rY-hhBwHsA9w5Qf6ql4HegBAuHrkUCZbxgW8BTZkNlBuwlZOJ4c
: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; }
}