我有一个asp,我有一个单选按钮,为用户选择一个角色。在aspx中,我想改变用户的角色,删除旧的并添加新的,这很简单。
问题是我得到的ApplicationUserManager有所有的异步方法。Async和asp页面不能很好地相处,出现以下错误:
此时无法启动异步操作。异步操作只能在异步处理程序或模块内启动,或者在页面生命周期中的某些事件期间启动。如果在执行页面时发生此异常,请确保页面标记为<%@页面Async="true“%>。此异常还可能表示有人试图调用"async void“方法,这在ASP.NET请求处理中通常是不受支持的。相反,异步方法应该返回一个Task,调用者应该等待它。
对于产生此错误的异步尝试,我调用异步任务。
protected async void GrantPrivlege_Click(object sender, EventArgs e)
{
ApplicationUserManager manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>();
string groupId = AspHelper.StringGuid(Request.Url.Segments[3]);
string userId = Request.Url.Segments[4];
IList<string> roles = await WaitGetRoles(userId);
foreach (string roleStr in roles) {
await WaitRemoveFromRole(userId, roleStr);
}
ApplicationUser.RoleEnum role = (ApplicationUser.RoleEnum)Enum.Parse(typeof(ApplicationUser.RoleEnum), PrivilegeList.SelectedValue, true);
await WaitAddToRole(userId, role.ToString());
Response.Redirect("/Admin/GroupAdmin/" + groupId);
}
protected async Task<IList<string>> WaitGetRoles(string userId)
{
ApplicationUserManager manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>();
IList<string> roles = await manager.GetRolesAsync(userId);
return roles;
}
protected async Task<bool> WaitRemoveFromRole(string userId, string roleStr)
{
ApplicationUserManager manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>();
await manager.RemoveFromRoleAsync(userId, roleStr);
return true;
}
protected async Task<bool> WaitAddToRole(string userId, string roleStr)
{
ApplicationUserManager manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>();
await manager.AddToRoleAsync(userId, roleStr);
return true;
}真正令人困惑的形式是,Visual Studio项目附带的Admin Register页面有AddRole方法,没有异步调用。
注册页面和我的页面都是一个带有aspx.cs的aspx,它使用
ApplicationUserManager manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>();两者都是在onclick方法中完成的。我真的希望我使用UserManagerExtensions获得注册ApplicationUserManager,它有AddToRoles,而不是用Microsoft.AspNet.Identity管理所有异步。不同之处可能是登录时注册asp不登录,之后登录。
谁能告诉我如何获得一个UserManagerExtensions版本的ApplicationUserManager或如果这是不可能的,如何让异步在aspx可靠地工作。
我被阻止了,因为这一点,我将继续谷歌为解决方案。
发布于 2015-03-19 23:12:07
有趣的是,发布这个问题给了我一些新的谷歌术语来尝试,我找到了http://www.hanselman.com/blog/TheMagicOfUsingAsynchronousMethodsInASPNET45PlusAnImportantGotcha.aspx,它展示了如何在ASP.Net中进行异步aspx。
放置异步是真的,页面标签很酷,因为Visual Studio为我的所有调用添加了一个异步标签,神奇的是,我的等待异步调用工作得很好。
// I added Async="true" to my aspx page
<%@ Page Async="true" Title="Async" Language="C#" CodeBehind="Async.aspx.cs" Inherits="Whatever" %>
// and then in my aspx.cs file await GetRolesAsync() works now
public async Task LoadPage()
{
string userId = Request.Url.Segments[4];
ApplicationUserManager manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>();
IList<string> roles = await manager.GetRolesAsync(userId);
if (roles.Count > 0) {
PrivilegeList.SelectedValue = roles[0];
}
}
使用来自ApplicationUserManager的强制异步调用运行页面现在运行得很好。
https://stackoverflow.com/questions/29133500
复制相似问题