Login Controller
public ActionResult Index() { //return Content("hello index!"); return View(); } [HttpGet] public ActionResult Login() { return View(); } [HttpPost] public ActionResult Login(string username, string password) { if(username=="111"&&password=="111") { Session["UUU"] = "111"; return RedirectToAction("Index"); } else { return Content("登录失败!"); } }
Index View
<h2>Index</h2> <text>主页运行成功</text>
Login View
<form action="/Login/Login" method="post"> 用户名<input type="text" name="username" value="" /> 密码<input type="text" name="password" value="" /> <input type="submit" name="name" value="提交" /> </form>
CheckLoginFilter
using System.Web.Mvc;//别引用错了 public class CheckLoginFilter:IAuthorizationFilter { public void OnAuthorization(AuthorizationContext filterContext) { string controllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = filterContext.ActionDescriptor.ActionName; if (controllerName == "Login" && actionName == "Login") { } else { if (filterContext.HttpContext.Session["UUU"] == null) { //ContentResult contexts = new ContentResult(); //contexts.Content = ("没有登录"); //filterContext.Result=contexts; filterContext.HttpContext.Response.Redirect("/Login/Login"); } } } }
Global
RouteConfig.RegisterRoutes(RouteTable.Routes); GlobalFilters.Filters.Add(new CheckLoginFilter() );//添加filter