2014-11-14 4 views
2

Я использую SelfHost/Katana/Owin для моего WebServer. У меня есть контроллер там, где я хочу включить/отключить код в зависимости от аргумента командной строки во время запуска.Как отключить контроллер MVC по коду?

Есть ли простой способ сделать это в MVC?

Прямо сейчас я думаю о коде контроллера, чтобы вернуть код статуса HTTP-NotFound при отключении этой конфигурации, каких-либо лучших идей?

ответ

1

Вы можете выполнить перенаправление, которое приведет пользователей к другому контроллеру, объясняющему, что происходит.

т.е.

public class MyController : Controller { 
    private IConfigReader _configReader; 

    public MyController(IConfigReader configReader){ //not sure if you're doing dependency injection or not, so I'm injecting it 
     _configReader = configReader; 
    } 

    public ActionResult Index() { 
     if(!_configReader.IsEnabled) { 
      return RedirectToAction("Denied", "AuthController"); 
     } 

     //etc 

     return View(); 
    } 
} 
1

Вы можете создать атрибут, применить его к контроллеру и установите статическое свойство на этот атрибут во время запуска, и отказать в доступе (или возвращение «Не найдено»), когда флаг установлен.

3

Вы можете украсить свой контроллер обычным Action Filter.

public class ConfigActionFilter : ActionFilterAttribute { 
    // This method is called before a controller action is executed. 
    public override void OnActionExecuting(ActionExecutingContext filterContext) { 
    if(someConfigSetting) { 
     filterContext.Result = new RedirectToRouteResult("Error", someRouteValues); 
    } 
    } 
    ... 
} 

Использование:

[ConfigActionFilter] 
public class MyController : Controller { 
    ... 
} 

Больше here.

1

В качестве альтернативы, вы можете реализовать пользовательские AuthorizationAttribute и положить его на контроллер

public class AuthorizationAdminAttribute : AuthorizeAttribute 
    { 
     protected override bool AuthorizeCore(HttpContextBase httpContext) 
     { 
      if (/*check for argument*/) 
      { 
       return false; 
      } 

      return true; 
     } 

     public override void OnAuthorization(AuthorizationContext filterContext) 
     { 
      if (AuthorizeCore(filterContext.HttpContext)) 
      { 
       // ** IMPORTANT ** 
       // Since we're performing authorization at the action level, the authorization code runs 
       // after the output caching module. In the worst case this could allow an authorized user 
       // to cause the page to be cached, then an unauthorized user would later be served the 
       // cached page. We work around this by telling proxies not to cache the sensitive page, 
       // then we hook our custom authorization code into the caching mechanism so that we have 
       // the final say on whether a page should be served from the cache. 

       HttpCachePolicyBase cachePolicy = filterContext.HttpContext.Response.Cache; 
       cachePolicy.SetProxyMaxAge(new TimeSpan(0)); 
       cachePolicy.AddValidationCallback(CacheValidateHandler, null /* data */); 
      } 
      else 
      {     
       filterContext.Result = new HttpNotFoundResult(); 
      } 
     } 

     private void CacheValidateHandler(HttpContext context, object data, ref HttpValidationStatus validationStatus) 
     { 
      validationStatus = OnCacheAuthorization(new HttpContextWrapper(context)); 
     } 
    } 
Смежные вопросы