Protected
(コントローラーとして)というビューフォルダーがあり、複数のビューを指す複数のアクションがあると仮定すると、次のようになります。
- コントローラー/アクションをアクションフィルターで装飾します。次に例を示します。
[SimpleMembership]
- そのアクションフィルターで、セッション変数の存在と内容を確認するだけです
SignIn
正しくない場合はにリダイレクトします
コードで:
public class SimpleMembershipAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
//redirect if not authenticated
if (filterContext.HttpContext.Session["myApp-Authentication"] == null ||
filterContext.HttpContext.Session["myApp-Authentication"] != "123")
{
//use the current url for the redirect
string redirectOnSuccess = filterContext.HttpContext.Request.Url.AbsolutePath;
//send them off to the login page
string redirectUrl = string.Format("?ReturnUrl={0}", redirectOnSuccess);
string loginUrl = "/Protected/SignIn" + redirectUrl;
filterContext.HttpContext.Response.Redirect(loginUrl, true);
}
}
}
とあなたのコントローラー
public class ProtectedController : Controller
{
[SimpleMembership]
public ActionResult Index()
{
return View();
}
public ActionResult SignIn()
{
return View();
}
[HttpPost]
public ActionResult SignIn(string pwd)
{
if (pwd == "123")
{
Session["myApp-Authentication"] = "123";
return RedirectToAction("Index");
}
return View();
}
}
全体を装飾したい場合は、そこに到達するためにメソッドを外部controller
に移動する必要があります。認証を受ける必要があります。SignIn
ソースコード:
シンプルなMVC3ソリューションhttp://cl.ly/JN6Bをダウンロードするか、 GitHubで自由にコードを表示できます。