ASP.Net MVC 路由到帐户

发布于 2024-10-20 01:59:11 字数 1429 浏览 2 评论 0原文

我需要创建一个具有以下验证的 aspnet mvc 应用程序 http://domain.com/accounta /controller/view/id,一旦在数据库中验证了该帐户,就必须检查它是否应该在url中继续,否则客户将被重定向到不存在帐户的页面,我发现的问题是在每个控制器方法中我都必须进行验证?还有更安宁的事吗?

例如:

public ActionResult Index()
    {
        if ((host != null) && (host.IndexOf(".") < 0))
        {
            sessao = SessionController.GetInstance();
            if (sessao.Conta.dsHost != null)
            {
                return View(sessao.Conta);
            }
            else
            {
                using (var contexto = new ThalentoEntities())
                {
                    sessao.Conta = contexto.TH_Conta.Single(q => q.dsHost == host && q.flAtivo == true);
                    if (sessao.Conta.dsHost != null)
                        return View(sessao.Conta);
                    else
                        return Redirect("/erro/no_account");
                }
            }
        }
        else
        {
            return Redirect("/erro/no_account");
        }
        return View();
    }

上面是控制器中每个方法的代码..

以及下面的 global.asax 代码

routes.MapRoute(
            "Default",
            "{controller}/{action}/{id}",
            new { host= UrlParameter.Optional, controller = "principal", action = "index", id = UrlParameter.Optional } 
        );  

I'm need to create a aspnet mvc app that has following verification http://domain.com/accounta/controller/view/id, this account has to be checked once in the database is validated and if it should continue in the url, otherwise the customer will be redirected to a page of nonexistent account, the problem I found is that in every controller method I'll have to be validated? There is a more peaceful for it?

ex:

public ActionResult Index()
    {
        if ((host != null) && (host.IndexOf(".") < 0))
        {
            sessao = SessionController.GetInstance();
            if (sessao.Conta.dsHost != null)
            {
                return View(sessao.Conta);
            }
            else
            {
                using (var contexto = new ThalentoEntities())
                {
                    sessao.Conta = contexto.TH_Conta.Single(q => q.dsHost == host && q.flAtivo == true);
                    if (sessao.Conta.dsHost != null)
                        return View(sessao.Conta);
                    else
                        return Redirect("/erro/no_account");
                }
            }
        }
        else
        {
            return Redirect("/erro/no_account");
        }
        return View();
    }

abovethe code of each method in controllers..

and bellow code of global.asax

routes.MapRoute(
            "Default",
            "{controller}/{action}/{id}",
            new { host= UrlParameter.Optional, controller = "principal", action = "index", id = UrlParameter.Optional } 
        );  

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

明媚殇 2024-10-27 01:59:11

您可以使用AuthorizeAttribute。示例:

public class CustomAuthorizeAttrinute : AuthorizeAttribute
{
    public override void OnAuthorization(AuthorizationContext filterContext)
    {
        base.OnAuthorization(filterContext);

        // override standard error result
        if (filterContext.Result is HttpUnauthorizedResult)
        {
            string url = "~/account/logon";

            if (filterContext.HttpContext.Request != null)
                url += "?rb=" + filterContext.HttpContext.Request.RawUrl;

            if (LoginLib.IsLogged())
                LoginLib.Logout();

            filterContext.Result = new RedirectResult(url);
        }
    }
}

public class AdminAuthorizeAttribute : CustomAuthorizeAttrinute
{
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        return LoginLib.IsLogged<Admin>();
    }
}

然后在控制器中

[AdminAuthorize]
public ActionResult Index()
{
    var model = new FooModel();

    model.Secret = "This is for admins only!";

    return View(model);
}

You can use AuthorizeAttribute. Example:

public class CustomAuthorizeAttrinute : AuthorizeAttribute
{
    public override void OnAuthorization(AuthorizationContext filterContext)
    {
        base.OnAuthorization(filterContext);

        // override standard error result
        if (filterContext.Result is HttpUnauthorizedResult)
        {
            string url = "~/account/logon";

            if (filterContext.HttpContext.Request != null)
                url += "?rb=" + filterContext.HttpContext.Request.RawUrl;

            if (LoginLib.IsLogged())
                LoginLib.Logout();

            filterContext.Result = new RedirectResult(url);
        }
    }
}

public class AdminAuthorizeAttribute : CustomAuthorizeAttrinute
{
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        return LoginLib.IsLogged<Admin>();
    }
}

And then in controller

[AdminAuthorize]
public ActionResult Index()
{
    var model = new FooModel();

    model.Secret = "This is for admins only!";

    return View(model);
}
浊酒尽余欢 2024-10-27 01:59:11

我将从路由开始 - 您应该教路由引擎识别 url 中的帐户,具体方法如下:

routes.MapRoute(
        "AccountUrl",
        "{account_name}/{controller}/{action}/{id}",
        new { host= UrlParameter.Optional, account_name = "", controller = "principal", action = "index", id = UrlParameter.Optional } 
    ); 

您应该在 Global.asax 中的“默认”路由之前添加此代码。

然后,您需要找出一种在每个操作之前执行帐户验证逻辑的方法。您可以使用过滤器来实现这一点。这是您的案例的参考代码:

public class ValidateAccountAttribute: FilterAttribute, IActionFilter {
    public void OnActionExecuting(ActionExecutingContext filterContext) {
        if (filterContext.RouteData.Values.ContainsKey("account_name") ||
            !IsAccountExists((string)filterContext.RouteData.Values["account_name"]))
            filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new {controller = "account", action = "login"}));
    }

    private bool IsAccountExists(string accountName) {
        // TODO: Implement
        throw new NotImplementedException();
    }

    public void OnActionExecuted(ActionExecutedContext filterContext) {
    }
}

它只是验证 account_name 路由值,如果为空,则重定向到登录页面。您可以将重定向网址更改为您需要的任何内容。

该过滤器可以全局应用(这可能不是您所需要的)、特定操作或整个控制器。

希望有帮助。

I'd start with the routing - you should teach the routing engine to recognize the account in the url, here's how:

routes.MapRoute(
        "AccountUrl",
        "{account_name}/{controller}/{action}/{id}",
        new { host= UrlParameter.Optional, account_name = "", controller = "principal", action = "index", id = UrlParameter.Optional } 
    ); 

You should add this code before the the "Default" route in your Global.asax.

Then you'll need to figure out a way to execute the account validation logic before each action. You can achieve this with Filters. Here's a reference code for your case:

public class ValidateAccountAttribute: FilterAttribute, IActionFilter {
    public void OnActionExecuting(ActionExecutingContext filterContext) {
        if (filterContext.RouteData.Values.ContainsKey("account_name") ||
            !IsAccountExists((string)filterContext.RouteData.Values["account_name"]))
            filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new {controller = "account", action = "login"}));
    }

    private bool IsAccountExists(string accountName) {
        // TODO: Implement
        throw new NotImplementedException();
    }

    public void OnActionExecuted(ActionExecutedContext filterContext) {
    }
}

It just validates the account_name routing value and redirects to login page if it's null. You can change the redirect url to whatever you need.

This filter can be applied globally (which is probably not what you need), to specific action or whole controller.

Hope that helps.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文