应用程序启动后立即调用Action方法

时间:2015-10-16 05:42:32

标签: c# asp.net-mvc stack-trace

我有一个MVC模块。一旦应用程序启动,它就会令人惊讶地重定向到AccessDenied操作方法。我尝试将日志放在哪个操作方法或应用程序的哪个部分调用此访问方法,以便在应用程序启动时立即启动。

所以我尝试将Environment.StackTrace放在日志中,但我无法从日志中获取任何内容。我的代码是这样的

public ActionResult AccessDenied(string errorMessage)
    {
        logger.Debug("Calling Access Denied from Base Controller \n Stacktrace is : \n" + Environment.StackTrace);
        ViewBag.ErrorMessage = errorMessage;
        return View("AccessDenied");
    }

此方法的日志是

{DEBUG}10/15 14:46:16 - Calling Access Denied from Base Controller 
 Stacktrace is : 
   at System.Environment.GetStackTrace(Exception e, Boolean needFileInfo)
   at System.Environment.get_StackTrace()
   at CMP.CBS.Websites.Receivable.Controllers.BaseController.AccessDenied(String errorMessage) in E:\Projects\CDP-AR\SourceCode\CDP-AR\CMP.CBS.Websites.Encounter\CMP.CBS.Websites.Receivable\Controllers\BaseController.cs:line 261
   at lambda_method(Closure , ControllerBase , Object[] )
   at System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters)
   at System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters)
   at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters)
   at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass42.<BeginInvokeSynchronousActionMethod>b__41()
   at System.Web.Mvc.Async.AsyncResultWrapper.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _)
   at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.End()
   at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult)
   at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass37.<>c__DisplayClass39.<BeginInvokeActionMethodWithFilters>b__33()
   at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass4f.<InvokeActionMethodFilterAsynchronously>b__49()
   at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass37.<BeginInvokeActionMethodWithFilters>b__36(IAsyncResult asyncResult)
   at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.End()
   at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult)
   at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass25.<>c__DisplayClass2a.<BeginInvokeAction>b__20()
   at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass25.<BeginInvokeAction>b__22(IAsyncResult asyncResult)
   at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.End()
   at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult)
   at System.Web.Mvc.Controller.<>c__DisplayClass1d.<BeginExecuteCore>b__18(IAsyncResult asyncResult)
   at System.Web.Mvc.Async.AsyncResultWrapper.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar)
   at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.End()
   at System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult)
   at System.Web.Mvc.Async.AsyncResultWrapper.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar)
   at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.End()
   at System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult)
   at System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult)
   at System.Web.Mvc.MvcHandler.<>c__DisplayClass8.<BeginProcessRequest>b__3(IAsyncResult asyncResult)
   at System.Web.Mvc.Async.AsyncResultWrapper.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar)
   at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.End()
   at System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult)
   at System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result)
   at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
   at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
   at System.Web.HttpApplication.ApplicationStepManager.ResumeSteps(Exception error)
   at System.Web.HttpApplication.ResumeStepsFromThreadPoolThread(Exception error)
   at System.Web.HttpApplication.AsyncEventExecutionStep.OnAsyncEventCompletion(IAsyncResult ar)
   at System.Web.HttpAsyncResult.Complete(Boolean synchronous, Object result, Exception error, RequestNotificationStatus status)
   at System.Web.SessionState.SessionStateModule.PollLockedSessionCallback(Object state)
   at System.Threading._TimerCallback.TimerCallback_Context(Object state)
   at System.Threading.ExecutionContext.runTryCode(Object userData)
   at System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData)
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
   at System.Threading._TimerCallback.PerformTimerCallback(Object state)

我的RouteConfig的内容是

public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Login", action = "Login", id = UrlParameter.Optional },
            namespaces: new[] { "CMP.CBS.Websites.Receivable.Login" }
            );

           //routes.MapRoute(
           // "Default",
           //"{controller}/{action}/{id}",
           //new { controller = "Login", action = "Login", id = UrlParameter.Optional },
           //new[] { "CMP.CBS.Websites.Receivable.Login" }
           //);

            routes.MapRoute(
              name: "ARListing",
              url: "{controller}/{action}/{id}",
              defaults: new { controller = "ARListing", action = "ARListing", id = UrlParameter.Optional }
            );
        }
  

我试过通过ReSharper找到这个动作方法的用法,并且没有这种动作方法的直接调用。它有3-4个引用,都来自另一个动作方法。但是StackTrace没有任何这样的痕迹。

     

PS:此行为仅在实时/测试服务器上,因为在本地我没有与之交互的另一个模块。

编辑:按照Jenny O&#39; Reilly的要求添加控制器和项目设置的更多信息 -

客户端(测试/实时服务器)上有一个MVC应用程序模块试图与我的新MVC模块交互,但我无法访问它。当用户第一次单击指向我的模块的链接时,它会重定向到拒绝访问。 PS:它只是第一次发生。

我在Global.asax中有记录器,它添加了它的日志 Gobal.asax文件看起来像 -

protected void Application_Start()
        {
            // Initialize log4net
            log4net.ILog logger = log4net.LogManager.GetLogger("ApplicationStart");
            XmlConfigurator.Configure();
            logger.Debug("[CMP] Application Start ");

            AreaRegistration.RegisterAllAreas();

            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
        }

用户需要访问ARListing页面,该页面包含Url.AbsolutePath(表示操作方法和控制器),例如来自其他模块的/Receivable/ARListing/ARListing

我的ARListingController喜欢

[CheckLoggedIn]
[AllowedToSeeThePage]
public class ARListingController : BaseController
{
  public ActionResult ARListing(string patient)
    {
       // Some Code to calculation, long enough to post here
    }
 }

BaseController个文件,其中包含构造函数和一个AccessDenied操作方法。

   public class BaseController : CMPControllerBase
    {
        public BaseController()
        {
          // Some Calculation and setting up some flags
          // No redirection code
        }
       public ActionResult AccessDenied(string errorMessage)
        {
            logger.Debug("Calling Access Denied from Base Controller \n Stacktrace is : \n" + Environment.StackTrace);
            ViewBag.ErrorMessage = errorMessage;
            return View("AccessDenied");
        }
    }

在CMPControllerBase中,还有一个构造函数但没有重定向代码。

我没有从CheckLoggedIn重定向到AccessDenied 但在AllowedToSeeThePage我重定向到访问被拒绝和该文件的代码看起来像 -

public class AllowedToSeeThePageAttribute : ActionFilterAttribute
    {
      public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
          logger.Debug("Custom Filter: Executing CustomAttr's OnActionExecuting");
          if (baseController != null && !baseController.IsAllowedToSeeThisPage && !filterContext.RequestContext.HttpContext.Response.IsRequestBeingRedirected)
            {
                logger.Debug("IsAllowedtoSeeThis Page : " + baseController.IsAllowedToSeeThisPage.ToString());
                logger.Debug("Custom Filter: trying to redirect to AccessDenied");

                string errorMessage = "";
                if (!baseController.HasValidRecordForPatient)
                {
                    errorMessage = "No record of PatInformation entry found for this patient";
                }
                else if (!baseController.IsAllowedToSeeThisPage)
                {
                    errorMessage = "You do not have valid counties to see this patient details";
                }
                string url = new UrlHelper(filterContext.RequestContext).Action("AccessDenied", "Base", new { errorMessage });
                filterContext.RequestContext.HttpContext.Response.Redirect(url);
                logger.Debug("Custom Filter: Redirected to AccessDenied" + errorMessage);
            }
        }
    }

和日志看起来像 -

{DEBUG}10/15 14:46:08 - [CMP] Application Start 
{DEBUG}10/15 14:46:15 - Called BaseController from : /Receivable/Base/AccessDenied
{DEBUG}10/15 14:46:16 - Calling Access Denied from Base Controller 
 Stacktrace is : 
   at System.Environment.GetStackTrace(Exception e, Boolean needFileInfo)
   at System.Environment.get_StackTrace()
   at CMP.CBS.Websites.Receivable.Controllers.BaseController.AccessDenied(String errorMessage) in E:\Projects\CDP-AR\SourceCode\CDP-AR\CMP.CBS.Websites.Encounter\CMP.CBS.Websites.Receivable\Controllers\BaseController.cs:line 261
   at lambda_method(Closure , ControllerBase , Object[] )
    .. goes on as above stacktrace mentioned 

请建议我为什么要调用此操作方法。

0 个答案:

没有答案