简体   繁体   中英

C# -Asp.net MVC Home/Index page redirect to login page

I've been develop a site for sometime but recently had this problem ,home/index page always redirect to login page ,and you can't see it unless you're logged in,Home Controller is surrounded with [AllowAnonymous] my defulat route is still the same .

routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );

I don't what can cause this problem ,I've never had this before, I've tried adding and removing [AllowAnonymous] ,still the same problem ,but the weird thing is Index is the only action in home controller require login,else work fine

[AllowAnonymous]
 public class HomeController : Controller
    {
public ActionResult Index()
        {
            try
            {
                using (ApplicationDbContext db = new ApplicationDbContext())
                {

                    var types = (from r in db.FeedBack
                                 select new FeedBackView { ID = r.ID, Name = r.Name, Jop = r.Jop, Body = r.Body }).Take(7).ToList();
                    var SlidersList = (from r in db.Sliders
                                       select new SliderView { Description = r.Description, Title = r.Title, ImageURL = r.ImageURL }).ToList();
                    var FeaturesList = (from r in db.Features
                                        select new FeatureView { Description = r.Description, Title = r.Title, ImageURL = r.ImageURL }).ToList();
                    var AccordionList = (from r in db.Accordion
                                         select new AccordionView { Description = r.Description, Title = r.Title, ImageURL = r.ImageURL }).ToList();
                    var ServicesList = (from r in db.Services
                                        select new ServiceView { Body = r.Body, Name = r.Name, ImageURL = r.ImageURL, Glaphicon = r.Glaphicon, ID = r.ID }).Take(6).ToList();

                    var portfolioTypesList = (from r in db.PortfolioTypes
                                              select new PortfolioTypeView { Name = r.Name, ID = r.ID, filter = r.filter }).Take(5).ToList();
                    List<PortfolioView> Portfolios = new List<PortfolioView>();
                    List<PortfolioView> toadd = new List<PortfolioView>();
                    portfolioTypesList.ForEach(r =>
                    {
                        //Portfolios.AddRange((from s in db.Portfolios
                        //                     where s.PortfolioTypeID == r.ID
                        //                     select new PortfolioView { TypeName = r.Name, ID = s.ID, filter = r.filter, ProjectName = s.ProjectName }
                        //                         ).Take(6).ToList());

                        toadd = (from s in db.Portfolios
                                 where s.PortfolioTypeID == r.ID
                                 select new PortfolioView { TypeName = r.Name, ID = s.ID, filter = r.filter, ProjectName = s.ProjectName }).Take(6).ToList();
                        Portfolios.AddRange(toadd);
                    });

                    var x = new List<PortfolioView>();
                    PortfolioImage im = new PortfolioImage();
                    Portfolios.ForEach(r =>
                    {
                        im = db.PortfolioImages.Where(s => s.PortfolioID == r.ID).FirstOrDefault();
                        if (im != null)
                        {
                            x.Add(new PortfolioView()
                            {
                                ID = r.ID,
                                TypeName = r.TypeName,
                                ProjectName = r.ProjectName,
                                URL = im.ImageURL,
                                filter = r.filter
                            });
                        }
                        else
                        {
                            x.Add(new PortfolioView()
                            {
                                ID = r.ID,
                                TypeName = r.TypeName,
                                ProjectName = r.ProjectName,
                                URL = "",
                                filter = r.filter
                            });
                        }
                    }
                           );

                    var Articels = (from e in db.Articles
                                    select new ArticleViewModel
                                    {
                                        Body = e.Body,
                                        Title = e.Title,
                                        ImageURL = e.ImageURL,
                                        ID = e.ID
                                    }).Take(3).ToList();

                    //var Social = db.Others.FirstOrDefault();
                    //ViewBag.Social = SocialMedia.convert(Social);                
                    ViewBag.Articels = Articels;
                    ViewBag.portfolioTypesList = portfolioTypesList;
                    ViewBag.Portfolios = x;
                    ViewBag.ServicesList = ServicesList;
                    ViewBag.AccordionList = AccordionList;
                    ViewBag.SliderList = SlidersList;
                    ViewBag.FeaturesList = FeaturesList;
                    ViewBag.FeedBackGo = types;
                    return View();
                }

            }
            catch (Exception ex)
            {
                return RedirectToAction("Error");
            }

        }
}

Have you tried custom attributes?

For instance let's create an attribute called CustomAuthorize

public class CustomAuthorize: AuthorizeAttribute    
 {

     protected override void HandleUnauthorizedRequest(AuthorizationContext    
     filterContext)    
     {     
           if (IsUserAuthenticated(filterContext.HttpContext))    
           {    
            filterContext.Result = new   RedirectResult("/Account/InvalidRole");    
           }    
           else    
           {    
            base.HandleUnauthorizedRequest(filterContext);    
           }    
     }

     private bool IsUserAuthenticated(HttpContextBase context)    
     {    
            return context.User != null && context.User.Identity != null &&     
            context.User.Identity.IsAuthenticated;    
     }

 }

By default the Authorize attribute lead to the login page if the user is not in the right role to access some part of your application.

Now to implement this you should do the following.

[CustomAuthorize(Roles="Admin,Manager")]
public class MyController
{

      // Everyone has access
      [AllowAnonymous]
      public ActionResult Index()
      {
      return View();
      }

      // Only Admin and Manager roles have access, everyone else is denied
      public ActionResult About()
      {
      return View();
      } 

}

Remember to put the attribute [AllowAnonymous] in cases where everyone can access the Action method. Inside the 'public' method you can include the following to allow role-specific implementations:

if(this.User.IsInRole("Administrator"))
{

}

With that you will be redirected to /Account/InvalidRole if you don't have the required role. And if you are good to go the page should render normally.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM