Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
404 views
in Technique[技术] by (71.8m points)

c# - How require authorization within whole ASP .NET MVC application

I create application where every action beside those which enable login should be out of limits for not logged user.

Should I add [Authorize] annotation before every class' headline? Like here:

namespace WebApplication2.Controllers {
[Authorize]
    public class HomeController : Controller {




        public ActionResult Index() {
            return View();
        }

        public ActionResult About() {
            ViewBag.Message = "Your application description page.";

            return View();
        }

        public ActionResult Contact() {
            ViewBag.Message = "Your contact page.";

            return View();
        }
    }
}

or there is a shortcut for this? What if I want to change rules for one and only action in particular controller?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Simplest way is to add Authorize attribute in the filter config to apply it to every controller.

public class FilterConfig
{
    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new HandleErrorAttribute());

        //Add this line
        filters.Add(new AuthorizeAttribute());
    }
}

Another way is to have all of your controllers inheriting from a base class. This is something I do often as there is almost always some shared code that all of my controllers can use:

[Authorize]
public abstract class BaseSecuredController : Controller
{
    //Various methods can go here
}

And now instead of inheriting from Controller, all of your controllers should inherit this new class:

public class MySecureController : BaseSecuredController
{
}

Note: Don't forget to add AllowAnonymous attribute when you need it to be accessible to non-logged in users.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...