asp.net MVC認可問題
-
23-09-2019 - |
質問
私は自分のコントローラに認証を追加しようとしていますし、それが働いていない...
私は確信している私のプログラムでは見ていないけど、
を追加します[Authorize]
私のコントローラ内のフィルタが動作していない、ましてや
のようなもの[Authorize(Roles = "Manager")]
私は新しいMVCプロジェクトを作成するときに提供されるデフォルトのアプリケーションでこの作業を取得することができました(私はログインしていないよ場合つまり、私は、ログイン画面に「約」タブのリダイレクトを作ることができています)ので、私は、私は私のアプリを構築してきたように、私は道に沿って物事をマックしていると仮定します。私はこの問題を解決するために探している必要がありどこ誰を知っていますか?私は、ユーザーが持っているし、彼らが役割を持っています。私は、自動作成されASP.netスキーマを使用しています。私は上下私のweb.configファイルを検討していると私はこれまでかなりの新たなんだが、何も場違いであるように思いません。私の許可フィルタが動作していないなぜ私は見当がつかない。?ます。
解決
私はこの問題を解決するためにカスタム属性を書きました。次のようにあなたは、コントローラのメソッドを属性することができます:
[RequiresRole(Role="Admin")]
public ActionResult Index()
{
int i = 5 + 5;
return View();
}
次のように属性のコードは....
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
namespace Web.Controllers
{
public class RequiresRoleAttribute : ActionFilterAttribute
{
public string Role { get; set; }
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (string.IsNullOrEmpty(Role))
{
throw new InvalidOperationException("No role specified.");
}
string redirectOnSuccess = filterContext.HttpContext.Request.Url.AbsolutePath;
string redirectUrl = string.Format("?returnUrl={0}", redirectOnSuccess);
string loginUrl = FormsAuthentication.LoginUrl + redirectUrl;
if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
{
filterContext.HttpContext.Response.Redirect(loginUrl, true);
}
else
{
bool isAuthorised = filterContext.HttpContext.User.IsInRole(this.Role);
if (!isAuthorised)
{
filterContext.HttpContext.Response.Redirect(loginUrl, true);
}
}
}
}
}
所属していません StackOverflow