UpdateAsync方法在web api中不起作用?

时间:2017-04-05 07:26:03

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

我正在使用web api mvc c#.i am register创建用于用户注册的小型演示成功使用web api.now中的'注册'的用户我想要使用此方法也编辑此用户我怎么能这样做我不知道任何人都知道请告诉我。我的代码我将在一个方法中管理添加/编辑调用,所以我将首先检查id上的条件是否为null然后添加并且id不为null然后去编辑,但如何编辑此记录和角色。

这是我的方法:

  [Route("Register")]
    public async Task<IHttpActionResult> Register(RegisterBindingModel model)
    {            
        try
        {
            if (model.Id == "")
            {          
              //here is for add user method         
                var user = new ApplicationUser() { UserName = model.Email, Email = model.Email,PhoneNumber = model.PhoneNumber };
                IdentityResult result = await UserManager.CreateAsync(user, model.Password);
                if (result.Succeeded)
                {
                    var UsersContext = new ApplicationDbContext();
                    var res = UsersContext.Users.Where(x => x.UserName == user.UserName).FirstOrDefault();
                    var UserId = res.Id;
                    await UserManager.AddToRoleAsync(UserId, model.UserRole);
                    return Ok(result);
                }
                return Ok(result);
            }
            else
            {
               //here i want write edit code
                var UsersContext = new ApplicationDbContext();
                var Team = UsersContext.Users.Find(model.Id);

                Team.UserName = model.UserName;
                Team.Email = model.Email;
                Team.PhoneNumber = model.PhoneNumber;
                IdentityResult result = await UserManager.UpdateAsync(Team); //here getting error.
                return Ok(result);  
            }                
            return Ok("Done");
        }
        catch (Exception ex)
        {                
        }
        return Ok();
    }  

1 个答案:

答案 0 :(得分:1)

<强>更新:

首先检查您是否将值传递给所有必填字段

在控制器类调用大括号 {

之后保留此 UserStore
if (model.Id == "")
 {
  //Add new user code
 }
else
 {
  var context = myUserStore.Context as ApplicationDbContext;
  var Team = context.Users.Find(model.Id);
  //change the field value what ever you want to update
  context.Users.Attach(Team);
  context.Entry(Team).State = EntityState.Modified;
  context.Configuration.ValidateOnSaveEnabled = false;
  await context.SaveChangesAsync();
  return Ok("Updated");
 }

然后在你的Register()Post方法中,按照下面这样做,

{{1}}

希望有所帮助:)