[AllowAnonymous]
public class AccountController : BaseController
{
[HttpPost]
public ActionResult LoginGo(Login form)
{
Session.RemoveAll();
Session["LoginInfo"] = null;
LoginData loginData = new LoginData();
try
{
if (ValidateLogin(form))
{
loginData.loginStatus = "00";
loginData.userId = form.userId;
loginData.userName = "使用者名稱";
FormsAuthenticationTicket authTicket = LoginProcess(form.userId);
string encryptedTicket = FormsAuthentication.Encrypt(authTicket);
HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
Response.Cookies.Add(authCookie);
return RedirectToAction("Login", "Account");
}
else
{
return RedirectToAction("Login", "Account");
}
}
catch (Exception ex)
{
return RedirectToAction("Login", "Account");
}
}
private bool ValidateLogin(Login form)
{
return true;
}
private FormsAuthenticationTicket LoginProcess(string userId)
{
string roles = "test";
FormsAuthenticationTicket authTicket =
new FormsAuthenticationTicket(
1,
userId,
DateTime.Now,
DateTime.Now.AddMinutes(20),
false,
roles
);
return authTicket;
}
}
所有的Controller都繼承BaseController,驗證寫在BaseController[Authorize],若Method或Class不需要驗證則加上[AllowAnonymous]
- [Authorize]
- public class BaseController : Controller
- {
- protected static NLog.Logger _logger = NLog.LogManager.GetCurrentClassLogger();
- }
Web.config 配置