C#中登录验证FormsAuthentication
1:前台编写一个登录界面,这里为了简化,只有用户名和密码
代码如下:
<form method="post" action="/User/CheckLogin"> <div> <span>用户名</span><input type="text" id="username" name="username"/><br/> <span>密码</span><input type="text" id="password" name="password"/><br /> <input type="submit" id="submit" value="登录" /> </div> </form>
2:后台CheckLogin方法中,验证用户名和密码,
需要using System.Web.Security;
if (new UserService().ValidateUser(username, password))//验证方法 { FormsAuthentication.RedirectFromLoginPage(username, true);//个人理解就像SESSION中写入这个用户,后面可以读到 return Content("aaa"); }
3:配置WEB.CONFIG文件
<system.web>//这个节点下 <authentication mode="Forms"> <forms name=".checklogin" loginUrl="/User/UserLogin" defaultUrl="/index.htm" protection="All" timeout="30" path="/" requireSSL="false" slidingExpiration="false" enableCrossAppRedirects="false" cookieless="UseDeviceProfile" domain="" /> </authentication>
4:使用
只需要在需要用的地方(一般是方法,或者类)加上[Authorize]
如:
[Authorize] public class InitDataToolsController : Controller { //..... }
再如:
[HttpPost] [OpenSessionInViewFilter] [Authorize] public ActionResult addPlainLocation(string locationCode, string locationType, string comments) {}
如果验证不通过会自动调到登录界面,这个是在WEB.CONFIG文件中配置的