2015-11-02 12 views
-1

期待將身份驗證添加到MVC 5 Boilerplate template,下一段代碼在其自己的original sample project中運行良好,但將其內容集成到Boilerplate模板後,並試圖註冊一個新用戶,成爲一些相互矛盾的,出現一個瀏覽器異常,指着下面「的await」行:嘗試將身份驗證添加到ASP.NET MVC Boilerplate模板 - 異步/等待問題

// POST: /Account/Register 
[HttpPost] 
[AllowAnonymous] 
[ValidateAntiForgeryToken] 
public async Task<ActionResult> Register(RegisterViewModel model) 
{ 
    if (ModelState.IsValid) 
    { 
     var user = new ApplicationUser { UserName = model.Email, Email = model.Email }; 
 var result = await UserManager.CreateAsync(user, model.Password); 
 if (result.Succeeded) 
     { 
     string callbackUrl = await SendEmailConfirmationTokenAsync(user.Id, "Confirm your account"); 
     ViewBag.Message = "Check your email and confirm your account, you must be confirmed " 
         + "before you can log in."; 
     ViewBag.Link = callbackUrl; 
     return View("Info"); 
     } 
     AddErrors(result); 
    } 
    return View(model); 
} 

我已經在很多地方讀到,當一個異步的問題發生,人們建議,使之同步的,但我的情況下,許多事情會變得incompatible.I不知道如何保持這種方法異步因爲它的淵源in the template

+1

首先,這是一個警告,而不是一個錯誤。它並不妨礙你的應用程序工作,這只是一個跡象,你正在做一些奇怪的事情。其次,它是完全正確的 - 你的'GetItems'方法沒有任何'await's,所以聲明中的'async'關鍵字是無用的,並且該方法將是100%同步的 - 沒有理由返回一個'任務'要麼。 – Luaan

+0

瀏覽器提供了一個例外,我不能忽視這一點,請閱讀整個問題,包括模板討論。 –

+0

您是否將警告編譯爲錯誤? – Lee

回答

1

感謝Nikita1315的幫助,我能找到下一個配置語法是在startup.cs文件中丟失:

 ConfigureAuth(app); 

所以啓動類會是什麼樣子:

public partial class Startup 
{ 
    public void Configuration(IAppBuilder app) 
    { 
     ConfigureContainer(app); 
     ConfigureAuth(app); 
     FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); 
    } 
} 

所以,當我加入這個配置,而不需要修改任何異步方法,我可以註冊我的第一個用戶。

3

您的GetItems不需要await,所以它不應該是async。只要改變簽名:

private List<SyndicationItem> GetItems(CancellationToken cancellationToken) 

,並從改變調用代碼:

await GetItems(token); 

到:

GetItems(token); 
+0

那麼如果我使用Andrii提出的TaskCompletionSource ,那麼它對我的FeedServices.cs有效,但對於AccountController方法我仍然遇到同樣的問題。 –

+0

我讀過很多文章,說它將異步方法轉換爲同步,我想知道爲什麼模板作者使它們異步。 accountController由Rick Anderson製作:http://www.asp。net/mvc/overview/security/create-an-aspnet -mvc-5-web-app-with-email-confirmation-and-password-reset –

+0

@ Sami-L如果你有異步工作,你會想要一個異步控制器去做。你沒有任何異步工作,你正在做。 – Servy