生成具有自定义AuthorizeAttribute传回网址 [英] Generate a return Url with a custom AuthorizeAttribute

查看:168
本文介绍了生成具有自定义AuthorizeAttribute传回网址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个自定义属性授权:

I have a custom authorize attribute:

using System;
using System.Web.Mvc;
using System.Web.Routing;
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
public class MyAuthorizeAttribute : AuthorizeAttribute
{
    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        if (!filterContext.HttpContext.Request.IsAuthenticated)
        {
            filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new { controller = "Login", action = "Login" }));
        }
        else
        {
            base.HandleUnauthorizedRequest(filterContext);
        }
    }
}

...我用来装点某些控制器:

...that I use to decorate certain controllers:

[MyAuthorizeAttribute(Roles = "Superman, Batman, Spiderman")]
public class SuperHeroController : Controller
{
    // ....
}

任何人都可以请解释如何修改授权code,这样,如果授权失败,登录URL包括 RETURNURL (电流控制器/方法的URL) ?

Can anyone please explain how to amend the authorize code so that if authorization fails, the Login URL includes a ReturnUrl (URL of the current controller/method)?

这基本上是试图模仿Web窗体RETURNURL逻辑,但在智能方式使得我不必手动使用字符串的URL。

This is basically trying to imitate the web forms ReturnUrl logic but in a smart manner whereby I don't have to manually use a string for the URL.

推荐答案

终于想通了,虽然有人可能能够提出一个更好的办法...

Finally figured it out, although somebody might be able to suggest a better way...

filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new { controller = "Login", action = "Login", returnUrl = filterContext.HttpContext.Request.Url.GetComponents(UriComponents.PathAndQuery, UriFormat.SafeUnescaped) }));

这篇关于生成具有自定义AuthorizeAttribute传回网址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆