0

I have encountered the following code that attempts to handle an authentication exception in a custom STS web site. This looks passable, but on calling Controller.Execute, I get a NullReferenceException. I would like to avoid the annoying black box of calling this method and rather redirect directly to the action, or throw a custom exception and set up built in error handling to do the redirect when the custom exception is thrown. I actually need some advice on how to do either properly.

var logId = LogProvider.Current.LogError(LogLevel.Fatal,e.InnerException ?? e, "Unexpected error during user authentication: [{0}]", incomingPrincipal.Identity.Name);
var context = HttpContext.Current; 
var routeData = new RouteData();
routeData.Values.Add("controller", "Error");
routeData.Values.Add("action", "Index");
routeData.Values.Add("errorId", logId);
routeData.Values.Add("exceptionMessage", "");
IController controller = new ErrorController();
var ctx = new RequestContext(new HttpContextWrapper(context), routeData);
controller.Execute(ctx);
context.Response.End();\
ProfK
  • 49,207
  • 121
  • 399
  • 775

1 Answers1

0

See my answer here.

HttpContext.Current is not available until after the HttpApplication.Start event is finished executing, which could explain your NullReferenceException if this code is being called too early in the application lifecycle.

If being called after this, there is also a possibility that your incomingPrincipal.Identity value is null if the user is not signed in.

One other possibility is that IIS is causing you grief. You can try setting context.Response.TrySkipIisCustomErrors = true; to prevent IIS from interfering with your redirect.

Community
  • 1
  • 1
NightOwl888
  • 55,572
  • 24
  • 139
  • 212
  • `HttpContext.Current` is available, but maybe not the identity, as you suggest. This bug is on hold for a short while, but I will be back with more conclusive observations soon. – ProfK Dec 13 '14 at 11:36