【问题标题】:Checking the status of an External System on Application Startup在应用程序启动时检查外部系统的状态
【发布时间】:2014-09-22 11:20:48
【问题描述】:

我们正在开发一个 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");被点击,但用户没有被重定向。

【问题讨论】:

    标签: c# .net asp.net-mvc asp.net-mvc-4 global-asax


    【解决方案1】:

    您可以在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;
        } 
    }
    

    【讨论】:

    • 这个问题现在已经解决了
    【解决方案2】:

    我犯了一个愚蠢的错误。 Home Controller 仅限于经过身份验证的用户。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-03
      • 1970-01-01
      • 2014-02-27
      • 2017-08-14
      • 1970-01-01
      相关资源
      最近更新 更多