在应用程序启动时检查外部系统的状态
问题描述:
我们正在开发一个ASP.NET MVC Web应用程序,它依赖于另一个系统的一些数据。 (这个选择的优点超出了这个问题的范围)在应用程序启动时检查外部系统的状态
当我们的web应用程序启动时,我们需要它来检查其他系统的状态。我们通过使用HTTPCLient请求登录到它。
如果系统没有响应或凭据不正确,那么我们的系统不应该启动,并将用户重定向到错误页面。如果登录成功,我们从中获取大量数据,并将其放入本地缓存中。
我遇到的问题是用户没有定向到错误页面,而是被定向到我们的应用程序登录页面。
这是我的全球ASAX。
private bool _externalSystemAvailable;
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
AutomapperConfiguration.Configure();
_externalSystemAvailable = ExternalSystem.Login();
}
protected void Application_BeginRequest(object source, EventArgs e)
{
var app = (HttpApplication) source;
var ctx = app.Context;
FirstRequestInitialisation.Initialise(ctx, _externalSystemAvailable);
}
我有一个基于this,检查应用程序是否已经被初始化,执行必要的初始化后例行另一个类。我有这个类,这样就不会对每个请求执行检查。
public class FirstRequestInitialisation
{
private static bool _alreadyInitialized = false;
private static object _lock = new object();
public static void Initialise(HttpContext context, bool _xternalSystemAvailable)
{
if (_alreadyInitialized)
{
return;
}
lock (_lock)
{
if (_alreadyInitialized)
{
return;
}
}
if (!externalSystemAvailable)
{
HttpContext.Current.RewritePath("/Home/Error");
}
_alreadyInitialized = true;
}
}
的HttpContext.Current.RewritePath("/Home/Error");
被击中,但用户没有被重定向。
答
我的部分愚蠢的错误。家庭控制器仅限于经过认证的用户。
答
可以在Application_BeginRequest
protected void Application_BeginRequest(object source, EventArgs e)
{
if (!externalSystemAvailable)
{
Response.Redirect("/Home/Error", false);
Response.StatusCode = 301;
}
}
重定向用户,但有一个与上面的代码的问题,那就是通过调用Response.Redirect
你再创建新页面的请求,再次意味着,事件触发,再而和它陷入无限循环。
我觉得这样做更好的地方是在session_start:
protected void Session_Start(object source, EventArgs e)
{
if (Session.IsNewSession && !externalSystemAvailable)
{
Response.Redirect("/Home/Error", false);
Response.StatusCode = 301;
}
}
是的,我一直在下降已经无限循环路:) – MrBliz 2014-09-22 13:50:31
这个问题是固定的,反正现在 – MrBliz 2014-09-22 13:51:25