Add new empty MVC project. Then add a new controller in it.
Controller Code is as follows,
- public class DefaultController : Controller
- {
-
- [HttpGet]
- [AllowAnonymous]
-
- public ActionResult Index()
- {
- return View();
- }
-
-
- [HttpPost]
- [AllowAnonymous]
- public ActionResult Login()
- {
- string u = Request["use"];
- string p = Request["pass"];
- string name = AuthUser(u,p);
- if (!(String.IsNullOrEmpty(name)))
- {
- Session["UserName"] = name;
- return RedirectToAction("home", "Default");
- }
- return RedirectToAction("Index","Default");
- }
- public ActionResult home()
- {
- return View();
- }
- public string AuthUser(string username, string password)
- {
- if (password.Equals("123") && username.Equals("user"))
- return "User";
- else
- return null;
- }
-
- }
Index.cshtml code is,
- @{
- Layout = null;
- }
-
- <!DOCTYPE html>
-
- <html>
- <head>
- <meta name="viewport" content="width=device-width" />
- <title>Index</title>
- </head>
- <body>
- <div>
- @using(Html.BeginForm("Login","Default",FormMethod.Post))
- {
- <input type="text" name="use" placeholder="Enter The Name" /><br/>
- <input type="password" name="pass" placeholder="Enter The Password" /><br/>
- <input type="submit" value="submit" />
- }
- </div>
- </body>
- </html>
After adding the code to the controller and making views add a new class name, AuthorizationFilter, in App_Start Folder.
The Class Code is,
- public class AuthorizationFilter : AuthorizeAttribute, IAuthorizationFilter
- {
- public override void OnAuthorization(AuthorizationContext filterContext)
- {
- if (filterContext.ActionDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true)
- || filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true))
- {
-
- return;
- }
-
-
- if (HttpContext.Current.Session["UserName"] == null)
- {
- filterContext.Result = new RedirectResult("~/Default/Index");
- }
- }
- }
Now Open Global.asax
Add this line in protected void Application_Start()
- GlobalFilters.Filters.Add(new AuthorizationFilter());
In last open Web.config add this line in <system.web>
- <system.web>
- <sessionState timeout="1"></sessionState>
- </system.web>
You will be redirected to Index page when session expires and then no one has to log in again.