0

'ForbidResult' below is used, which causes a url redirect. Thus, Context.Items["data"] is lost for the redirected page, which is /MicrosoftIdentity/Account/AccessDenied?ReturnUrl=SomeSite.

 public class PermissionAttribute : TypeFilterAttribute
    {

        private class PermissionFilter : IAsyncActionFilter
        {

            public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
            {
                context.HttpContext.Items["data"] = "some data";
               
                var authorized = check_if_it_has_permissions();
                if (authorized)
                {
                    await next();
                }
                else
                {
                    context.Result = new ForbidResult();  //this is a url redirect using /MicrosoftIdentity/Account/AccessDenied?ReturnUrl=SomeSite        
                }
            }
        }
    }

partial_view_header.cshtml

<div id="header">
    @{
                Context.Items["data"]              
     }

</div>

Is it possible to keep the current url, and not change the url to '/MicrosoftIdentity/Account/AccessDenied?ReturnUrl=xxx', or a way to pass data to Acccount AccessDenied view?

Pingpong
  • 7,681
  • 21
  • 83
  • 209

1 Answers1

0

You can try to use Session,or you can pass data with querystring,here is a demo with session: PermissionFilter:

public class PermissionFilter : Attribute,IAsyncActionFilter
    {

        public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            context.HttpContext.Session.SetString("data", "some data");
            context.Result = new RedirectToRouteResult
                (
                new RouteValueDictionary(new
                {
                    action = "Account",
                    controller = "Home",
                    //data = "some data"
                }));
            return;


        }
    }

HomeController:

 [PermissionFilter]
        public IActionResult Index()
        {
            return View();
        }
public IActionResult Account() {
            TempData["data"] = HttpContext.Session.GetString("data");
            return View();
        }
Yiyi You
  • 16,875
  • 1
  • 10
  • 22
  • you are right. But we don't want to use session and querystring. The reason is security for querystring, and for session, it is not bening used. We want to avoid session if possible. – Pingpong Nov 09 '20 at 14:35
  • What about use cookie?you can refer to [this](https://stackoverflow.com/questions/14956027/how-to-pass-values-across-the-pages-in-asp-net-without-using-session)? – Yiyi You Nov 11 '20 at 03:40
  • cookie is also not safe. – Pingpong Nov 20 '20 at 18:06