开发者

ASP.Net MVC Route to Account

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
                        retu开发者_如何转开发rn 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 } 
        );  


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);
}


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜