MVC Form認證、許可權、異常日誌

來源:互聯網
上載者:User

標籤:http   io   ar   os   sp   java   for   on   log   

一、首先是登入:

public class AccountController : BaseController
{
public ActionResult Login()
{
//已經登入的,直接到預設首頁
if (HttpContext.Request.IsAuthenticated)
{
return Redirect(FormsAuthentication.DefaultUrl);
}
return View();
}

[HttpPost]
public ActionResult Login(string userName, string userPassword, string isRemember)
{
if (userName == "admin" && userPassword == "111")
{
Person p = new Person() { Name = userName, Roles = "admin", Age = 23, Email = "[email protected]", Ip = MD5Helper.MD5Encrypt(Request.UserHostAddress) };
bool remenber = isRemember == null ? false : true;
//把使用者物件儲存在票據裡
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, userName, DateTime.Now, DateTime.Now.AddTicks(FormsAuthentication.Timeout.Ticks), remenber, p.ObjToJson());
//加密票據
string hashTicket = FormsAuthentication.Encrypt(ticket);
HttpCookie userCookie = new HttpCookie(FormsAuthentication.FormsCookieName, hashTicket);
if (remenber)
{
userCookie.Expires = DateTime.Now.AddTicks(FormsAuthentication.Timeout.Ticks);
}
Response.Cookies.Add(userCookie);

string returnUrl =HttpUtility.UrlDecode(Request["ReturnUrl"]);
if (string.IsNullOrEmpty(returnUrl))
{
return RedirectToAction("Index", "Home");
}
else
{
return Redirect(returnUrl);
}
}
else
{
ViewData["Tip"] = "使用者名稱或密碼有誤!";
return View();
}
}
public ActionResult Logout()
{
//取消Session會話
Session.Abandon();
//刪除Forms驗證票證
FormsAuthentication.SignOut();
return RedirectToAction("Login", "Account");
}
}
}

二、許可權驗證 

public class AuthAttribute : ActionFilterAttribute
{
/// <summary>
/// 角色名稱
/// </summary>
public string Code { get; set; }
/// <summary>
/// 驗證許可權(action執行前會先執行這裡)
/// </summary>
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
//如果存在身份資訊
if (HttpContext.Current.User.Identity.IsAuthenticated)
{
Person person = new Models.UserInfo().UserLoginInfo;
string[] Role = person.Roles.Split(‘,‘);//擷取所有角色

if (person.Ip != Common.MD5Helper.MD5Encrypt(HttpContext.Current.Request.UserHostAddress))
{
ContentResult Content = new ContentResult();
Content.Content = string.Format("<script type=‘text/javascript‘>alert(‘為了您的帳號安全,請重新登入!‘);window.location.href=‘{0}‘;</script>", FormsAuthentication.LoginUrl);
filterContext.Result = Content;
}
else if (!Role.Contains(Code))//驗證許可權
{
//驗證不通過
ContentResult Content = new ContentResult();
Content.Content = "<script type=‘text/javascript‘>alert(‘您沒有足夠的許可權!‘);history.go(-1);</script>";
filterContext.Result = Content;
}
}
else
{
ContentResult Content = new ContentResult();
Content.Content = string.Format("<script type=‘text/javascript‘>alert(‘請先登入!‘);window.location.href=‘{0}?ReturnUrl={1}‘;</script>", FormsAuthentication.LoginUrl, HttpUtility.UrlEncode(HttpContext.Current.Request.RawUrl));
filterContext.Result = Content;
}
}
}

三、/// 異常處理

public class BaseController : Controller
{
/// <summary>
/// 異常處理
/// </summary>
/// <param name="filterContext"></param>
protected override void OnException(ExceptionContext filterContext)
{
// 記錄錯誤記錄檔
ErrorLog.Write(filterContext);
}

}
}

MVC Form認證、許可權、異常日誌

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.