【发布时间】:2018-10-02 09:47:27
【问题描述】:
我正在开发基于角色的授权。使用User.AddIdentity 成功定义角色后,当我退出页面时它会消失。
[AllowAnonymous]
[HttpPost]
public IActionResult Index(User user)
{
try
{
var currentUser = _UserService.login(user, _context);
if (currentUser.userID != 0)
{
CookieOptions options = new CookieOptions();
options.Expires = DateTime.Now.AddDays(1);
var identity = new ClaimsIdentity(new[] {
new Claim(ClaimTypes.Name, currentUser.NAME_SURNAME),
new Claim(ClaimTypes.Role, "Admin")
},
"ApplicationCookie");
User.AddIdentity(new ClaimsIdentity(identity));
var isin = User.IsInRole("Admin");
var cacheValue = _UserService.stringToMd5(currentUser.NAME_SURNAME);
Response.Cookies.Append("login_cache", cacheValue, options);
TempData["error"] = null;
return RedirectToAction("index", "home");
}
else
{
TempData["error"] = "Kullanıcı adı yada şifre yanlıştır.";
return RedirectToAction("index", "home");
}
}
catch(Exception ex){
TempData["error"] = ex.Message;
//TempData["error"] = "User not found.";
return RedirectToAction("index", "home");
}
}
[Area("Admin")]
[Authorize(Roles = "Admin")]
public class FaqController : Controller
{
....
}
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddDistributedMemoryCache();
services.AddSession();
services.AddSession(options => {
options.IdleTimeout = TimeSpan.FromMinutes(60);
});
services.AddMvc();
services.AddDbContext<ModelContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, IServiceProvider serviceProvider)
{
if (env.IsDevelopment())
{
app.UseBrowserLink();
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseAuthentication();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "admin",
template: "{area}/{controller=Home}/{action=Index}/{id?}");
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
【问题讨论】:
-
如何认证用户?请分享您的创业课程
-
我添加了startup.cs
标签: c# asp.net-core .net-core asp.net-core-mvc asp.net-core-2.1