Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

What is the best way to disable ASP.NET MVC controller conditionally?

I want to have an access to the controller actions if some value in web.config is "true" and 404 if it's "false"

Should I write my own attribute?

UPDATE: Looking for more elegant solution than action filter attribute (with an ability to pass not constant parameter to attribute constructor)

    [AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = true)]
    public class CloseForSomeSettingAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            bool mySettingValue = MySettingManager.GetMySettingValue();

            if (mySettingValue)
            {
                filterContext.Result = new HttpStatusCodeResult(404);
            }
            else
            {
                base.OnActionExecuting(filterContext);
            }
        }
    }
See Question&Answers more detail:os

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

1 Answer

The easiest would probably be to implement a custom action filter:

http://www.asp.net/mvc/tutorials/older-versions/controllers-and-routing/understanding-action-filters-cs

You can also conditionally add a route that matches that controller that would result in a 404 being returned.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...