如何在 MVC .net 核心中授权会话?
How to authorize a session in MVC .net core?
我想授权仅当用户登录时创建操作?我该如何实现?
ApplicationDBContext.cs
namespace BookReadingEvents.Data
{
public class ApplicationDbContext : DbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
{
}
public DbSet<BookReadingEvent> BookReadingEvents { get; set; }
public DbSet<Register> RegisterAccount { get; set; }
public DbSet<Login> LoginAccount { get; set; }
}
}
RegisterController.cs
namespace BookReadingEvents.Controllers
{
public class RegisterController : Controller
{
private readonly ApplicationDbContext _db;
[ActivatorUtilitiesConstructor]
public RegisterController(ApplicationDbContext db)
{
_db = db;
}
public IActionResult Index()
{
return RedirectToAction("Register");
}
// GET Register
public IActionResult Register()
{
return View();
}
//POST Register
[HttpPost]
public IActionResult Register(Register user)
{
if (ModelState.IsValid)
{
_db.RegisterAccount.Add(user);
_db.SaveChanges();
return RedirectToAction("Index");
}
return View(user);
}
}
}
LoginController.cs
public class LoginController : Controller
{
private readonly ApplicationDbContext _db;
[ActivatorUtilitiesConstructor]
public LoginController(ApplicationDbContext db)
{
_db = db;
}
public IActionResult Index()
{
return RedirectToAction("Login");
}
// GET Login
public IActionResult Login()
{
return View();
}
//POST Login
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Login(Login user)
{
if (ModelState.IsValid)
{
var obj = _db.RegisterAccount.Where(u => u.Email.Equals(user.Email) && u.Password.Equals(user.Password)).FirstOrDefault();
if (obj != null)
{
user.RegisterId = obj.RegisterId;
_db.LoginAccount.Add(user);
_db.SaveChanges();
HttpContext.Session.SetObjectAsJson("Register", obj);
return RedirectToAction("LoggedIn");
}
}
ModelState.AddModelError("", "Some Error Occured");
return RedirectToAction("Login");
}
public IActionResult LoggedIn()
{
var userDetails = HttpContext.Session.GetObjectFromJson<Register>("Register");
int? thisUserID = Convert.ToInt32(userDetails.RegisterId);
if (thisUserID != null)
{
return RedirectToAction("Index","Home");
}
else
{
return RedirectToAction("Login");
}
}
public IActionResult Logout()
{
HttpContext.Session.Clear();
//HttpContext.Session.Abandon();
return RedirectToAction("Index", "Home");
}
public IActionResult MyEvents()
{
return View();
}
}
}
SessionExtension.cs
public static class SessionExtension
{
public static void SetObjectAsJson(this ISession session, string key, object value)
{
session.SetString(key, JsonConvert.SerializeObject(value));
}
public static T GetObjectFromJson<T>(this ISession session, string key)
{
var value = session.GetString(key);
return value == null ? default(T) : JsonConvert.DeserializeObject<T>(value);
}
}
BookReadingEventController.cs
namespace BookReadingEvents.Controllers
{
public class BookReadingEventController : Controller
{
private readonly ApplicationDbContext _db;
public BookReadingEventController(ApplicationDbContext db)
{
_db = db;
}
public IActionResult Index()
{
IEnumerable<BookReadingEvent> objList = _db.BookReadingEvents;
return View(objList);
}
// GET Create
//[Authorize]
//InvalidOperationException: No authenticationScheme was specified,
//and there was no DefaultChallengeScheme found.
public IActionResult Create()
{
ViewBag.StartTimeDD = new List<string> { "00:00", "01:00", "02:00", "03:00" , "04:00", "05:00", "06:00", "07:00", "08:00" , "09:00" ,"10:00", "11:00", "12:00", "13:00", "14:00", "15:00", "16:00","17:00", "18:00", "19:00",
"20:00", "21:00", "22:00", "23:00"};
return View();
}
// POST Create
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Create(BookReadingEvent obj)
{
ViewBag.StartTimeDD = new List<string> { "00:00", "01:00", "02:00", "03:00" , "04:00", "05:00", "06:00", "07:00", "08:00" , "09:00" ,"10:00", "11:00", "12:00", "13:00", "14:00", "15:00", "16:00","17:00", "18:00", "19:00",
"20:00", "21:00", "22:00", "23:00"};
if (ModelState.IsValid)
{
_db.BookReadingEvents.Add(obj);
_db.SaveChanges();
return RedirectToAction("Index");
}
return View(obj);
}
public IActionResult Display(int id)
{
var obj = _db.BookReadingEvents.Find(id);
if (obj == null)
{
return NotFound();
}
return View(obj);
}
// GET Update
//[Authorize]
//InvalidOperationException: No authenticationScheme was specified,
//and there was no DefaultChallengeScheme found.
public IActionResult Update(int? id)
{
ViewBag.StartTimeDD = new List<string> { "00:00", "01:00", "02:00", "03:00" , "04:00", "05:00", "06:00", "07:00", "08:00" , "09:00" ,"10:00", "11:00", "12:00", "13:00", "14:00", "15:00", "16:00","17:00", "18:00", "19:00",
"20:00", "21:00", "22:00", "23:00"};
if (id == null || id == 0)
{
return NotFound();
}
var obj = _db.BookReadingEvents.Find(id);
if (obj == null)
{
return NotFound();
}
return View(obj);
}
// POST Update
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Update(BookReadingEvent obj)
{
if (ModelState.IsValid)
{
_db.BookReadingEvents.Update(obj);
_db.SaveChanges();
return RedirectToAction("Index");
}
return View(obj);
}
}
}
我想授权创建和更新操作,以便只有当用户登录后他们才能创建或更新表。我该如何实现?
我注意到当用户登录成功时,如果你想授权会话,你在登录方法中设置了一个 key
是 Register
的会话。您可以使用 IActionFilter
来实现它。我这里写个简单的demo。
过滤器
public class SessionFilter : Attribute,IActionFilter
{
public void OnActionExecuting(ActionExecutingContext context)
{
//if there is no session whitch key is "register", user will not access to specified action and redirect to login page.
var result = context.HttpContext.Session.GetObjectFromJson<T>("register");
if (result==null)
{
context.Result = new RedirectToActionResult("Login", "Login", null);
}
}
public void OnActionExecuted(ActionExecutedContext context)
{
}
}
然后您可以将[SessionFilter]
添加到您要保护的操作中。
[HttpPost]
[SessionFilter]
[ValidateAntiForgeryToken]
public IActionResult Create(BookReadingEvent obj)
{.......}
我想授权仅当用户登录时创建操作?我该如何实现?
ApplicationDBContext.cs
namespace BookReadingEvents.Data
{
public class ApplicationDbContext : DbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
{
}
public DbSet<BookReadingEvent> BookReadingEvents { get; set; }
public DbSet<Register> RegisterAccount { get; set; }
public DbSet<Login> LoginAccount { get; set; }
}
}
RegisterController.cs
namespace BookReadingEvents.Controllers
{
public class RegisterController : Controller
{
private readonly ApplicationDbContext _db;
[ActivatorUtilitiesConstructor]
public RegisterController(ApplicationDbContext db)
{
_db = db;
}
public IActionResult Index()
{
return RedirectToAction("Register");
}
// GET Register
public IActionResult Register()
{
return View();
}
//POST Register
[HttpPost]
public IActionResult Register(Register user)
{
if (ModelState.IsValid)
{
_db.RegisterAccount.Add(user);
_db.SaveChanges();
return RedirectToAction("Index");
}
return View(user);
}
}
}
LoginController.cs
public class LoginController : Controller
{
private readonly ApplicationDbContext _db;
[ActivatorUtilitiesConstructor]
public LoginController(ApplicationDbContext db)
{
_db = db;
}
public IActionResult Index()
{
return RedirectToAction("Login");
}
// GET Login
public IActionResult Login()
{
return View();
}
//POST Login
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Login(Login user)
{
if (ModelState.IsValid)
{
var obj = _db.RegisterAccount.Where(u => u.Email.Equals(user.Email) && u.Password.Equals(user.Password)).FirstOrDefault();
if (obj != null)
{
user.RegisterId = obj.RegisterId;
_db.LoginAccount.Add(user);
_db.SaveChanges();
HttpContext.Session.SetObjectAsJson("Register", obj);
return RedirectToAction("LoggedIn");
}
}
ModelState.AddModelError("", "Some Error Occured");
return RedirectToAction("Login");
}
public IActionResult LoggedIn()
{
var userDetails = HttpContext.Session.GetObjectFromJson<Register>("Register");
int? thisUserID = Convert.ToInt32(userDetails.RegisterId);
if (thisUserID != null)
{
return RedirectToAction("Index","Home");
}
else
{
return RedirectToAction("Login");
}
}
public IActionResult Logout()
{
HttpContext.Session.Clear();
//HttpContext.Session.Abandon();
return RedirectToAction("Index", "Home");
}
public IActionResult MyEvents()
{
return View();
}
}
}
SessionExtension.cs
public static class SessionExtension
{
public static void SetObjectAsJson(this ISession session, string key, object value)
{
session.SetString(key, JsonConvert.SerializeObject(value));
}
public static T GetObjectFromJson<T>(this ISession session, string key)
{
var value = session.GetString(key);
return value == null ? default(T) : JsonConvert.DeserializeObject<T>(value);
}
}
BookReadingEventController.cs
namespace BookReadingEvents.Controllers
{
public class BookReadingEventController : Controller
{
private readonly ApplicationDbContext _db;
public BookReadingEventController(ApplicationDbContext db)
{
_db = db;
}
public IActionResult Index()
{
IEnumerable<BookReadingEvent> objList = _db.BookReadingEvents;
return View(objList);
}
// GET Create
//[Authorize]
//InvalidOperationException: No authenticationScheme was specified,
//and there was no DefaultChallengeScheme found.
public IActionResult Create()
{
ViewBag.StartTimeDD = new List<string> { "00:00", "01:00", "02:00", "03:00" , "04:00", "05:00", "06:00", "07:00", "08:00" , "09:00" ,"10:00", "11:00", "12:00", "13:00", "14:00", "15:00", "16:00","17:00", "18:00", "19:00",
"20:00", "21:00", "22:00", "23:00"};
return View();
}
// POST Create
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Create(BookReadingEvent obj)
{
ViewBag.StartTimeDD = new List<string> { "00:00", "01:00", "02:00", "03:00" , "04:00", "05:00", "06:00", "07:00", "08:00" , "09:00" ,"10:00", "11:00", "12:00", "13:00", "14:00", "15:00", "16:00","17:00", "18:00", "19:00",
"20:00", "21:00", "22:00", "23:00"};
if (ModelState.IsValid)
{
_db.BookReadingEvents.Add(obj);
_db.SaveChanges();
return RedirectToAction("Index");
}
return View(obj);
}
public IActionResult Display(int id)
{
var obj = _db.BookReadingEvents.Find(id);
if (obj == null)
{
return NotFound();
}
return View(obj);
}
// GET Update
//[Authorize]
//InvalidOperationException: No authenticationScheme was specified,
//and there was no DefaultChallengeScheme found.
public IActionResult Update(int? id)
{
ViewBag.StartTimeDD = new List<string> { "00:00", "01:00", "02:00", "03:00" , "04:00", "05:00", "06:00", "07:00", "08:00" , "09:00" ,"10:00", "11:00", "12:00", "13:00", "14:00", "15:00", "16:00","17:00", "18:00", "19:00",
"20:00", "21:00", "22:00", "23:00"};
if (id == null || id == 0)
{
return NotFound();
}
var obj = _db.BookReadingEvents.Find(id);
if (obj == null)
{
return NotFound();
}
return View(obj);
}
// POST Update
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Update(BookReadingEvent obj)
{
if (ModelState.IsValid)
{
_db.BookReadingEvents.Update(obj);
_db.SaveChanges();
return RedirectToAction("Index");
}
return View(obj);
}
}
}
我想授权创建和更新操作,以便只有当用户登录后他们才能创建或更新表。我该如何实现?
我注意到当用户登录成功时,如果你想授权会话,你在登录方法中设置了一个 key
是 Register
的会话。您可以使用 IActionFilter
来实现它。我这里写个简单的demo。
过滤器
public class SessionFilter : Attribute,IActionFilter
{
public void OnActionExecuting(ActionExecutingContext context)
{
//if there is no session whitch key is "register", user will not access to specified action and redirect to login page.
var result = context.HttpContext.Session.GetObjectFromJson<T>("register");
if (result==null)
{
context.Result = new RedirectToActionResult("Login", "Login", null);
}
}
public void OnActionExecuted(ActionExecutedContext context)
{
}
}
然后您可以将[SessionFilter]
添加到您要保护的操作中。
[HttpPost]
[SessionFilter]
[ValidateAntiForgeryToken]
public IActionResult Create(BookReadingEvent obj)
{.......}