从 Net 4.5版本 迁移至NetCore3.1时,WebApi中直接dynamic传参,使用会报错,错误信息如下: {"'System.Text.Json.JsonElement' does not contain a definition for 'LoginName'"} System.Exception {Microsoft.CSharp.RuntimeBinder.RuntimeBinderException}
而 在Net 4.5版本版本下不会报错,使用正常。报错代码如下:
#region AddUser
/// <summary>
/// 更新用户信息
/// </summary>
/// <returns></returns>
[Route("Company/AddUser")]
[HttpPost]
public string AddUser(dynamic objdyn)
{
string json = "";
LogHelper log = LogHelper.GetInstance();
try
{
CUserInfo cui = new CUserInfo();
CUserInfoBase xbase = new CUserInfoBase();
xbase.LoginName = Convert.ToString(objdyn.LoginName);
bool checkflag = cui.CheckLoginName(xbase.LoginName);
if (checkflag)
{
xbase.Password = StrHelper.PwdMD5(Convert.ToString(objdyn.Password));
xbase.UserName = Convert.ToString(objdyn.UserName);
xbase.Telephone = Convert.ToString(objdyn.Telephone);
xbase.Email = Convert.ToString(objdyn.Email);
xbase.Sex = Convert.ToByte(objdyn.Sex);
xbase.State = Convert.ToByte(objdyn.State);
xbase.UserType = Convert.ToByte(objdyn.UserType);
xbase.SalesmanId = Convert.ToInt32(objdyn.SalesMan);
xbase.CompanyId = Convert.ToInt32(objdyn.Company);
xbase.AddTime = DateTime.Now;
xbase.Memo = Convert.ToString(objdyn.Memo);
int flag = cui.Add(xbase);
if (flag > 0)
{
json = CFormatJson.HttpResult("0", "添加成功", null);
}
else
{
json = CFormatJson.HttpResult("1", "操作失败", null);
}
}
else
{
json = CFormatJson.HttpResult("2", "登录名重复", null);
}
}
catch (Exception ex)
{
log.WriteErrorLog("Company/AddUser-" + ex.Message);
json = CFormatJson.HttpResult("1", "系统异常:" + ex.Message, null);
}
return json;
}
#endregion
解决方案如下:
增加转换一下即可使用:
dynamic objdyn = JsonConvert.DeserializeObject(Convert.ToString(obj));
string name=objdyn.LoginName;