How to redirect to a dynamic login URL in ASP.NET MVC

后端 未结 4 784
情书的邮戳
情书的邮戳 2020-12-04 05:59

I\'m creating a multi-tenancy web site which hosts pages for clients. The first segment of the URL will be a string which identifies the client, defined in Global.asax using

4条回答
  •  遥遥无期
    2020-12-04 06:34

    In the RTM version of ASP.NET MVC, the Cancel property is missing. This code works with ASP.NET MVC RTM:

    using System;
    using System.Web;
    using System.Web.Mvc;
    using System.Web.Mvc.Resources;
    
    namespace ePegasus.Web.ActionFilters
    {
        public class CustomAuthorize : AuthorizeAttribute
        {
            public override void OnAuthorization(AuthorizationContext filterContext)
            {
                base.OnAuthorization(filterContext);
                if (filterContext.Result is HttpUnauthorizedResult)
                {
                    filterContext.Result = new RedirectToRouteResult(
                        new System.Web.Routing.RouteValueDictionary
                            {
                                    { "langCode", filterContext.RouteData.Values[ "langCode" ] },
                                    { "controller", "Account" },
                                    { "action", "Login" },
                                    { "ReturnUrl", filterContext.HttpContext.Request.RawUrl }
                            });
                }
            }
        }
    }
    

    Edit: You may want to disable the default forms authentication loginUrl in web.config - in case somebody forgets you have a custom attribute and uses the built in [Authorize] attribute by mistake.

    Modify the value in web.config:

     
    

    Then make an action method 'ERROR' that logs an error and redirects the user to the most generic login page you have.

提交回复
热议问题