C# 登录并向操作添加“授权”属性后,无法访问控制器操作
我已经设置了一个简单的登录页面,当我的用户单击登录按钮时,就可以登录。用户在登录时获得分配的角色。为了测试它是否有效,我已经完成了以下登录代码:C# 登录并向操作添加“授权”属性后,无法访问控制器操作,c#,asp.net,asp.net-mvc,login,asp.net-mvc-5,C#,Asp.net,Asp.net Mvc,Login,Asp.net Mvc 5,我已经设置了一个简单的登录页面,当我的用户单击登录按钮时,就可以登录。用户在登录时获得分配的角色。为了测试它是否有效,我已经完成了以下登录代码: [HttpPost] [ActionName("Login")] public ActionResult Login(LoginViewModel model) { if (ModelState.IsValid) { st
[HttpPost]
[ActionName("Login")]
public ActionResult Login(LoginViewModel model)
{
if (ModelState.IsValid)
{
string userName = model.Username;
string[] userRoles = new string[5];
userRoles[0] = "Administrator";
ClaimsIdentity identity = new ClaimsIdentity(DefaultAuthenticationTypes.ApplicationCookie);
identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, userName));
// userRoles.ToList().ForEach((role) => identity.AddClaim(new Claim(ClaimTypes.Role, role)));
identity.AddClaim(new Claim(ClaimTypes.Role, userRoles[0]));
identity.AddClaim(new Claim(ClaimTypes.Name, userName));
AuthenticationManager.SignIn(identity);
return RedirectToAction("Success");
}
else
{
return View("Login",model);
}
}
我在MVC操作中添加了一个Authorize属性,只是想看看用户在登录后是否真的能够访问它。。。我是这样做的:
[Authorize(Roles="Administrator")]
public ActionResult Register()
{
var model = new UserRegistrationViewModel();
var countries = Connection.ctx.Countries.OrderBy(x => x.CountryName).ToList();
model.Countries = new SelectList(countries, "CountryId", "CountryName");
return View(model);
}
但由于某些原因,当我尝试访问以下内容时:
mywebsite.com/user/register
它告诉我:
HTTP Error 401.0 - Unauthorized
You do not have permission to view this directory or page.
可能是什么
编辑:
以下是用户登录后声明和身份的快照:
第二个:
我认为您获得401是因为您的用户没有“管理员”角色。在后续请求中检查您的用户(身份),我不确定角色是否保留在cookie中-您可能需要自己找到一种方法来保留角色。您是否可以确保您拥有cookie中间件?比如说, Startup.cs
有人有什么想法吗,伙计们/<代码>标识.AddClaim(新声明(ClaimTypes.Role,“管理员”)代码>你能硬编码
管理员并再次调试吗?您能显示UserController中使用的Authorize属性吗?好的,稍后我会尝试。您对[Authorize(Roles=“Administrator”)]所说的是,没有“Administrator”权限的其他用户无法访问此操作role@Win我试过了,也是一样。。。素食主义者,是的,这就是我要测试的本质。。。从上面的代码中可以看出,用户在登录时获得“管理员”角色。。。因此,我应该能够访问的行动没有任何问题,但它说,我没有权限,甚至在登录后…我已经包括了登录后的快照。。。你能调查一下吗?:)我只有map.signal();在启动类的我的配置函数中。。。我试试这个:)
[assembly: OwinStartup(typeof(YourApplicationName.Startup))]
namespace YourApplicationName
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/Login")
});
}
}
}