[英]Custom Authentication in ASP.NET MVC 4 app
我正在將一個舊的ASP.NET Web窗體應用程序遷移到ASP.NET MVC 4.我對ASP.NET MVC不是很熟悉,所以如果這是一個愚蠢的問題我會道歉。 簡而言之,我的ASP.NET Web Forms應用程序使用以下代碼行在登錄時重定向用戶:
FormsAuthentication.RedirectFromLoginPage(username, true);
我以為我可以復制並粘貼此代碼。 但是,我注意到它試圖將用戶重定向到“default.aspx”。 這個電話的MVC相當於什么?
謝謝!
表單身份驗證通常提供一個returnUrl
作為查詢字符串參數(這是我假設FormsAuthentication.RedirectFromloginPage(username, true)
正在使用的。)話雖如此,請在returnUrl
中接收的登錄操作中添加一個參數,然后在你的登錄動作。
[HttpPost]
public ActionResult Login(LoginViewModel model, String returnUrl)
{
if (ModelState.IsValid)
{
// perform login
if (YourFormsAuthentication.YourLoginMethod(mode.username, model.password))
{
//
// Set auth cookie, log user in, etc.
//
// Now check for returnUrl and make sure it's present and
// valid (not redirecting off-site)
if (!String.IsNullOrEmpty(returnUrl) && Url.IsLocalUrl(returnUrl))
{
return Redirect(returnUrl);
}
// no returnUrl provided, direct them to default landing page
return RedirectToRoute("Home");
}
else
{
ModelState.AddError("", "Username or password are incorrect.");
}
}
return View(model);
}
在控制器的登錄方法中添加一個參數字符串returnUrl。
然后檢查它是否為空或為空。 如果沒有重定向。
[HttpPost]
public ActionResult LogOn(LogOnModel model, string returnUrl)
{
// Do your login
// if success
if (!String.IsNullOrEmpty(returnUrl))
{
return Redirect(returnUrl);
}
}
在您的視圖中還傳遞returnUrl(將是Request.Url)
<%: Html.ActionLink("Log On", "LogOn", "ControllerName", new { returnUrl = Request.Url }, null)%>
您有完整的示例: http : //www.c-sharpcorner.com/UploadFile/cd3310/using-mvc-Asp-Net-tools-create-simple-login-form/
使用特定操作的控制器查看
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Login(YourModel model)
{
if (!ModelState.IsValid)
{
return View("Login", model);
}
return RedirectToAction("Index");
}
在MVC 4中,如果您創建一個新應用程序並選擇Internet應用程序選項,模板將為表單身份驗證連接所有內容,並將您設置為使用SimpleMembership提供程序,這樣可以更輕松地自定義用戶配置文件並添加對輕松插入OAuth的支持。 您應該在web.config中包含以下條目。
<authentication mode="Forms">
<forms loginUrl="~/Account/Login" timeout="2880" />
</authentication>
如果用戶未經過身份驗證或授權,這會告訴應用程序重定向到loginUrl。 然后,您只需在控制器或操作上使用AuthorizeAttribute 。 如果要使用基於角色的授權或僅使用角色,則可以向此屬性添加角色。 在這里,我為HomeController的Contact操作添加了AuthorizeAttribute。
[Authorize(Roles="Admin")]
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
此操作位於由MVC 4 Internet模板創建的默認HomeController上。 用戶體驗是,如果他們單擊主頁上的“聯系人”選項卡並且未登錄,則會將其重定向到登錄頁面。 成功登錄后,他們將被重定向回“聯系人”頁面。 因此,MVC 4 Internet應用程序可以為您提供所有連接,您無需明確處理重定向。 有關自定義SimpleMembership提供程序的更多信息, 您可以閱讀此博客 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.