2017-09-01 57 views
0

我正在使用web api/mvc 5並試圖在一段時間內停止任何進一步的端點。是否有可能爲基於ActionFilterAttribute的全局過濾器做到這一點?如何防止一段時間內的webapi端點

public override void OnActionExecuting(HttpActionContext filterContext) 
{ 
    bool isSystemShutdown = _systemService.isSystemShutdownScheduled(); 
    if (isSystemShutdown == true) 
    { 
     return; 
    } 
    base.OnActionExecuting(filterContext); 
} 

回答

3

您應該返回迴應。根據需要將filterContext的Response屬性設置爲有效響應。

這裏我回來了200 OK。您可以隨時更新它返回任何你想要的(自定義數據/消息等)

public override void OnActionExecuting(HttpActionContext filterContext) 
{ 
    bool isSystemShutdown = _systemService.isSystemShutdownScheduled(); 
    if (isSystemShutdown) 
    { 
     var r= new HttpResponseMessage(HttpStatusCode.OK); 
     filterContext.Response = r; 
     return; 
    } 
    base.OnActionExecuting(filterContext); 
} 

現在你可以在Application_Start事件global.asax.cs

GlobalConfiguration.Configuration.Filters.Add(new YourFilter()); 

全球註冊這個如果要指定一個信息,到調用者代碼,你可以做到這一點。

public override void OnActionExecuting(HttpActionContext filterContext) 
{ 
    bool isSystemShutdown = _systemService.isSystemShutdownScheduled(); 
    if (isSystemShutdown) 
    { 
     var s = new { message = "System is down now" }; 
     var r= filterContext.Request.CreateResponse(s); 
     filterContext.Response = r; 
     return; 
    } 
    base.OnActionExecuting(filterContext); 
} 

這將返回一個JSON結構,如下面的200 OK響應代碼。

{"message":"System is down now"} 

如果你想發送不同的響應狀態代碼,你可以在filterContext.Response.StatusCode屬性值根據需要設置到的HTTPStatus代碼。

相關問題