5 c# asp.net-core asp.net-core-webapi
我正在我的网站上创建一个小应用程序,以使用API请求获取用户信息.
[HttpGet("GetUserInfo/{user_id}/{fields?}")]
public IActionResult GetUserInfo(string user_id, params string[] fields)
{
var userProfile = _userManager.GetUserProfile(user_id);
if (userProfile == null)
{
return Ok(null);
}
var userInfo = new
{
id = userProfile.UserId,
email = userProfile.Email,
name = userProfile.Name,
// I don't want to define a null property here:
picture_url = fields.Contains("picture_url") ? "path" : null
};
if (fields.Contains("picture_url"))
{
userInfo.picture_url = "";
}
return Ok(userInfo);
}
Run Code Online (Sandbox Code Playgroud)
当一个请求是有效的,则它返回其包含3个属性默认JSON对象:id,email,和name.
现在,我想检查一下,如果请求想要获得有关此用户的更多信息,就像picture_url.所以,我试过了:
if (fields.Contains("picture_url"))
{
// error in this line
userInfo.picture_url = "path";
}
Run Code Online (Sandbox Code Playgroud)
'<anonymous type:string id,string email,string name>'不包含'picture_url'的定义,也没有扩展方法'picture_url'接受类型'<anonymous type的第一个参数:string id,string email,string name >'可以找到(你是否错过了使用指令或汇编引用?)
如何动态地向匿名对象添加一些属性?
匿名类型是不可变的,您只能在创建实例时创建和设置属性.这意味着您需要创建所需的确切对象.所以你可以这样做:
if (fields.Contains("picture_url"))
{
return Ok(new
{
id = userProfile.UserId,
email = userProfile.Email,
name = userProfile.Name,
picture_url = "path"
});
}
return Ok(new
{
id = userProfile.UserId,
email = userProfile.Email,
name = userProfile.Name
});
Run Code Online (Sandbox Code Playgroud)
另一种选择是使用a Dictionary<string, object>.例如:
var userInfo = new Dictionary<string, object>
{
{"id", userProfile.UserId},
{"email", userProfile.Email},
{"name", userProfile.Name}
};
if (fields.Contains("picture_url"))
{
// error in this line
userInfo.Add("picture_url", "path");
}
return Ok(userInfo);
Run Code Online (Sandbox Code Playgroud)
此对象将序列化为相同的JSON结构:
{"id":1,"email":"email@somewhere.com","name":"Bob","picture_url":"path"}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3059 次 |
| 最近记录: |