2016-03-01 85 views
2

我想更改MVC5 ASP.NET Application的默認註冊操作。我的情況是,授權用戶(如admin)將登錄並且可以創建新用戶。然而,使用下面的代碼片段,創建用戶後,當前登錄用戶將更改爲註冊用戶。ASP.NET MVC5身份:避免在註冊後更改登錄用戶

如何更改以下代碼以避免更改登錄用戶?

// POST: /Account/Register 
[HttpPost] 
[AllowAnonymous] 
[ValidateAntiForgeryToken] 
public async Task<ActionResult> Register(RegisterViewModel model) 
{ 
    if (ModelState.IsValid) 
    { 
     var user = new ApplicationUser() { UserName = model.UserName,Name=model.Name }; 
     var result = await UserManager.CreateAsync(user, model.Password); 
     if (result.Succeeded) 
     { 
      await SignInAsync(user, isPersistent: false); 
      return RedirectToAction("Index", "Home"); 
     } 
     else 
     { 
      AddErrors(result); 
     } 
    } 

    // If we got this far, something failed, redisplay form 
    return View(model); 
} 
+1

註冊用戶在 「SignInAsync」 之稱,因爲後登錄,其主要工作是登錄用戶..刪除該行「SignInAsync」。 –

+1

您將需要一個單獨的管理員操作,它不是'[AllowAnonymous]'並且檢查該人員是admin;還傳入兩個用戶名(管理員,新用戶)。 – Jasen

回答

0

刪除SignInAsync並添加[授權]註釋:

[HttpPost] 
[Authorize] 
[ValidateAntiForgeryToken] 
public async Task<ActionResult> Register(RegisterViewModel model) 
{ 
    if (ModelState.IsValid) 
    { 
     var user = new ApplicationUser() { UserName = model.UserName,Name=model.Name }; 
     var result = await UserManager.CreateAsync(user, model.Password); 
     if (result.Succeeded) 
     { 
      //await SignInAsync(user, isPersistent: false); 
      return RedirectToAction("Index", "Home"); 
     } 
     else 
     { 
      AddErrors(result); 
     } 
    } 

    // If we got this far, something failed, redisplay form 
    return View(model); 
} 
1

只要做到這一點:

if (result.Succeeded) 
{ 
    if (!User.IsAuthenticated) // if they're already logged in, don't log in again 
     await SignInAsync(user, isPersistent: false); 
    return RedirectToAction("Index", "Home"); 
}