Programing

조치 필터 속성에서 경로 재 지정

lottogame 2020. 7. 2. 07:46
반응형

조치 필터 속성에서 경로 재 지정


어떤 것은에서 리디렉션을 할 수있는 가장 좋은 방법입니다 ActionFilterAttribute. I는있다 ActionFilterAttribute라고 IsAuthenticatedAttributeFilter하고는 세션 변수의 값을 확인. 변수가 false이면 응용 프로그램이 로그인 페이지로 리디렉션되기를 원합니다. 경로 이름을 사용하여 리디렉션하는 것을 선호 SystemLogin하지만이 시점의 모든 리디렉션 방법이 좋습니다.


filterContext.Result를 설정하십시오.

경로 이름으로 :

filterContext.Result = new RedirectToRouteResult("SystemLogin", routeValues);

다음과 같은 작업을 수행 할 수도 있습니다.

filterContext.Result = new ViewResult
{
    ViewName = SharedViews.SessionLost,
    ViewData = filterContext.Controller.ViewData
};

사용하려는 경우 RedirectToAction:

보호 대상을 간단히 호출하는 RedirectToAction컨트롤러 ( 기본 컨트롤러에서 ) 공개 메소드를 작성할 수 RedirectToAction있습니다 System.Web.Mvc.Controller. 이 방법을 추가 하면 필터에서 사용자 에게 공개 전화를 걸 수 있습니다RedirectToAction .

public new RedirectToRouteResult RedirectToAction(string action, string controller)
{
    return base.RedirectToAction(action, controller);
}

그런 다음 필터는 다음과 같습니다.

public override void OnActionExecuting(ActionExecutingContext filterContext)
{
    var controller = (SomeControllerBase) filterContext.Controller;
    filterContext.Result = controller.RedirectToAction("index", "home");
}

자신의 코드를 호출하는 경우 리디렉션 대신 다음을 사용할 수 있습니다.

actionContext.Result = new RedirectToRouteResult(
    new RouteValueDictionary(new { controller = "Home", action = "Error" })
);

actionContext.Result.ExecuteResult(actionContext.Controller.ControllerContext);

순수한 리디렉션은 아니지만 불필요한 오버 헤드없이 유사한 결과를 제공합니다.


MVC4를 사용하고 있으며 승인 위반시 사용자 지정 HTML 화면을 리디렉션하기 위해 다음과 같은 접근 방식을 사용했습니다.

확장 AuthorizeAttributeCutomAuthorizer에 우선 OnAuthorization하고HandleUnauthorizedRequest

등록 CustomAuthorizerRegisterGlobalFilters.

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{

    filters.Add(new CustomAuthorizer());
}

아래 그림과 같이 unAuthorized액세스 호출 을 식별하고 HandleUnauthorizedRequest관련 컨트롤러 작업으로 리디렉션합니다.


public class CustomAuthorizer : AuthorizeAttribute
{

    public override void OnAuthorization(AuthorizationContext filterContext)
    {
        bool isAuthorized = IsAuthorized(filterContext); // check authorization
        base.OnAuthorization(filterContext);
        if (!isAuthorized && !filterContext.ActionDescriptor.ActionName.Equals("Unauthorized", StringComparison.InvariantCultureIgnoreCase)
            && !filterContext.ActionDescriptor.ControllerDescriptor.ControllerName.Equals("LogOn", StringComparison.InvariantCultureIgnoreCase))
        {

            HandleUnauthorizedRequest(filterContext);

        }
    }

    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        filterContext.Result =
       new RedirectToRouteResult(
           new RouteValueDictionary{{ "controller", "LogOn" },
                                          { "action", "Unauthorized" }

                                         });

    }
}

다시 구현하거나 확장하려는 것처럼 들립니다 AuthorizeAttribute. 그렇다면 ActionFilterAttributeASP.NET MVC가 더 많은 작업을 수행 할 수 있도록 하려면 상속하지 않아야 합니다.

Also, you want to make sure that you authorize before you do any of the real work in the action method - otherwise, the only difference between logged in and not will be what page you see when the work is done.

public class CustomAuthorizeAttribute : AuthorizeAttribute
{
    public override void OnAuthorization(AuthorizationContext filterContext)
    {
        // Do whatever checking you need here

        // If you want the base check as well (against users/roles) call
        base.OnAuthorization(filterContext);
    }
}

There is a good question with an answer with more details here on SO.


Try the following snippet, it should be pretty clear:

public class AuthorizeActionFilterAttribute : ActionFilterAttribute
{
  public override void OnActionExecuting(FilterExecutingContext filterContext)
  {
    HttpSessionStateBase session = filterContext.HttpContext.Session;
    Controller controller = filterContext.Controller as Controller;

    if (controller != null)
    {
      if (session["Login"] == null)
      {
        filterContext.Cancel = true;
        controller.HttpContext.Response.Redirect("./Login");
      }
    }

    base.OnActionExecuting(filterContext);
  }
}

Here is a solution that also takes in account if you are using Ajax requests.

using System;
using System.Web.Mvc;
using System.Web.Routing;

namespace YourNamespace{        
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
    public class AuthorizeCustom : ActionFilterAttribute {
        public override void OnActionExecuting(ActionExecutingContext context) {
            if (YourAuthorizationCheckGoesHere) {               
                string area = "";// leave empty if not using area's
                string controller = "ControllerName";
                string action = "ActionName";
                var urlHelper = new UrlHelper(context.RequestContext);                  
                if (context.HttpContext.Request.IsAjaxRequest()){ // Check if Ajax
                    if(area == string.Empty)
                        context.HttpContext.Response.Write($"<script>window.location.reload('{urlHelper.Content(System.IO.Path.Combine(controller, action))}');</script>");
                    else
                        context.HttpContext.Response.Write($"<script>window.location.reload('{urlHelper.Content(System.IO.Path.Combine(area, controller, action))}');</script>");
                } else   // Non Ajax Request                      
                    context.Result = new RedirectToRouteResult(new RouteValueDictionary( new{ area, controller, action }));             
            }
            base.OnActionExecuting(context);
        }
    }
}

you could inherit your controller then use it inside your action filter

inside your ActionFilterAttribute class:

   if( filterContext.Controller is MyController )
      if(filterContext.HttpContext.Session["login"] == null)
           (filterContext.Controller as MyController).RedirectToAction("Login");

inside your base controller:

public class MyController : Controller 
{
    public void  RedirectToAction(string actionName) { 
        base.RedirectToAction(actionName); 
    }
}

Cons. of this is to change all controllers to inherit from "MyController" class


This works for me (asp.net core 2.1)

using JustRide.Web.Controllers;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;

namespace MyProject.Web.Filters
{
    public class IsAuthenticatedAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            if (context.HttpContext.User.Identity.IsAuthenticated)
                context.Result = new RedirectToActionResult(nameof(AccountController.Index), "Account", null);
        }
    }
}



[AllowAnonymous, IsAuthenticated]
public IActionResult Index()
{
    return View();
}

참고URL : https://stackoverflow.com/questions/5453338/redirect-from-action-filter-attribute

반응형