Problem with custom controller factory - asp.net-mvc

I've recently added Microsoft Unity to my MVC3 project and now I'm getting this error:
The controller for path '/favicon.ico' could not be found or it does not implement IController.
I do not really have a favicon.ico so I have no idea where that's coming from. And the weirdest thing is that the view is actually being rendered and THEN this error is being thrown... I am not sure if it's something wrong with my controller factory class because I got the code from some tutorial (I'm not to IoC - this is the first time I do that). Here's the code:
public class UnityControllerFactory : DefaultControllerFactory
{
IUnityContainer container;
public UnityControllerFactory(IUnityContainer _container)
{
container = _container;
}
protected override IController GetControllerInstance(System.Web.Routing.RequestContext requestContext, Type controllerType)
{
IController controller;
if(controllerType == null)
throw new HttpException(404, string.Format("The controller for path '{0}' could not be found or it does not implement IController.",
requestContext.HttpContext.Request.Path));
if(!typeof(IController).IsAssignableFrom(controllerType))
throw new ArgumentException(string.Format("Type requested is not a controller: {0}",
controllerType.Name),
"controllerType");
try
{
controller = container.Resolve(controllerType) as IController;
}
catch (Exception ex)
{
throw new InvalidOperationException(String.Format(
"Error resolving controller {0}",
controllerType.Name), ex);
}
return controller;
}
}
Any suggestions?
Thanks in advance!

This has nothing to do with your controller factory specifically, but it is something you can easily address.
If you are using a Webkit browser (Chrome specifically, Safari too- I think), a request to any website will automatically be accompanied by a request to '/favicon.ico'. The browser is attempting to find a shortcut icon to accompany your website and (for whatever reason) the default path for shortcut icons has been standardized to be '/favicon.ico'.
To avoid the error you're getting, simply define an IgnoreRoute() within the routing table of your MVC web application:
RouteTable.Routes.IgnoreRoute("{*favicon}", new { favicon = #"(.*/)?favicon.([iI][cC][oO]|[gG][iI][fF])(/.*)?" });
This will ensure that any request to '/favicon.ico' (or '/favicon.gif') will not be handled by MVC.

I have seen this done as well:
catch (Exception ex)
{
/*throw new InvalidOperationException(String.Format(
"Error resolving controller {0}",
controllerType.Name), ex);*/
base.GetControllerInstance(requestContext,controllerType);
}

Related

Is there a way to discriminate a specific System.Web.HttpException?

I've some "bad boys" users which call my website using controller that doesn't exist.
Such as www.myapp.com/.svn/, or www.myapp.com/wp-admin/.
The app basically throw a System.Web.HttpException, which this ExceptionMessage: The controller for path '...' was not found or does not implement IController.
Is there a way to exactly catch this "sub" System.Web.HttpException in a robust way? (not comparing the string of ExceptionMessage, of course).
Any sub InnerException type and/or some "code" which indicate that exact exception?
You might create a custom IControllerFactory, e.g. by deriving from DefaultControllerFactory.
Its GetControllerInstance method will be called with a null value for the controllerType argument, when no matching controller could be resolved.
At this point, you are ahead of the Exception.
IController GetControllerInstance(RequestContext requestContext, Type controllerType)
Here you decide how to handle the request, like e.g. logging and/or handling the request by a specific controller.
The example below shows how the ErrorController is being used as fallback, executing its Index action method.
class CustomControllerFactory : DefaultControllerFactory
{
protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
{
if (controllerType == null)
{
var routeData = requestContext.RouteData;
routeData.Values["controller"] = "Error";
routeData.Values["action"] = "Index";
controllerType = typeof(ErrorController);
}
return base.GetControllerInstance(requestContext, controllerType);
}
}
A custom controller factory gets installed from within e.g. Application_Start in Global.asax.cs using:
ControllerBuilder.Current.SetControllerFactory(new CustomControllerFactory());
Note that this doesn't guard you from a related exception in case the contoller does exist, but the action doesn't.
E.g. given a HomeController without an Ufo action method, the url www.myapp.com/home/ufo results in an Exception "A public action method 'ufo' was not found on controller '...HomeController".
A simple solution to handle such scenario is by overriding HandleUnknownAction in a custom base controller of which all your controllers inherit.
The example below shows how a shared Error view (Shared\Error.cshtml) gets executed.
public abstract class BaseController : Controller
{
protected override void HandleUnknownAction(string actionName)
{
View("Error").ExecuteResult(ControllerContext);
}
}
The problem as you have stated seems like a routing problem.
Have you tried a catch all route?... That is a route that is executed when no other route matches the request's path. The catch all route is defined last and seems like:
// Specific routes here...
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute(
"Catch-All",
"{*controller}",
new { controller = "Home", action = "Index" }
);
I tested with .NET Core MVC
// This is how it is configured in .NET Core MMVC
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
endpoints.MapControllerRoute(
name: "catch-all",
pattern: "{*controller}",
defaults: new { controller="Home", action="Index" });
});
I think that managing the excepion, as sugested in previous answers, is a good practice, but does not solve the routing problem you are facing.
You might want to take a look to this discussion regarding similiar problem with ASP.NET MVC:
ASP.NET MVC - Catch All Route And Default Route
Like #Amirhossein mentioned, since you are using .net 4.6 framework you can have a global exception catch inside the
Global.asax file something like:
protected void Application_Error(object sender, EventArgs e)
{
var ex = Server.GetLastError();
Debug.WriteLine(ex);
var httpEx = ex as HttpException;
var statusCode = httpEx?.GetHttpCode() ?? 500;
Server.ClearError();
...
}
or you can address this issue via IIS (since I presume you host your application on IIS) by adding a mapping rule (which in turn can be done in the web.config) or by adding a filter, or even a firewall rule (since by my account those kind of probing scans are not worth to be logged in your application - I believe they should be handled on another level)

Redirect to shared Error view from Global.asax on MVC unhandled exception

I've been reading about the different ways to perform error handling in ASP.MVC. I know about try/catch within a controller, and also about [HandleError] at controller-level.
However, I am trying to perform global error handling for unhandled exceptions that could occur anywhere in the application (the wow - we never expected a user to do that! type of thing). The result of this is that an email is sent to dev's:
This is working fine:
protected void Application_Error()
{
Exception last_ex = Server.GetLastError();
Server.ClearError();
// send email here...
Response.Redirect("/Login/Login");
}
Elsewhere in the application, should an error occur in a controller, we have this logic which provides a friendly error in our error view:
Error Model
namespace My.Models
{
public class ErrorViewModel
{
public string Summary { get; set; }
public string Description { get; set; }
}
}
Controller Code
if(somethingBad){
return View("Error", new ErrorViewModel { Summary = "Summary here", Description = "Detail here" });
}
My question is, is it possible to redirect to the error view passing the ErrorViewModel from within Global.asax, e.g.
// send email here...
Response.MethodToGetToView(new ErrorViewModel { Summary = "Error", Description = ex.Message });
From the Application_Error method, you can do something like:
RouteData routeData = new RouteData();
routeData.Values.Add("controller", "Error");
routeData.Values.Add("action","Error500");
routeData.Values.Add("Summary","Error");
routeData.Values.Add("Description", ex.Message);
IController controller = new ErrorController()
controller.Execute(new RequestContext(new HttpContextWrapper(Context), routeData));
This will return the view from the action result you specify here to the user's browser, so you will need a controller & action result that returns your desired error view (Error/Error500 in this example). It is not a redirect so is technically more correct (if an error occurs, you should return an HTTP 500 status immediately, not a 302 then a 500 as is often done).
Also, if you want to capture all 404's from all URLs (not just those that match a route), you can add the following route to the end of your route config
routes.MapRoute("CatchAllUrls", "{*url}", new { controller = "Error", action = "Error404" }, new string[] { "MyApp.Controllers" });

Exception Handling in ASP.NET MVC and Ajax - [HandleException] filter

All,
I'm learning MVC and using it for a business app (MVC 1.0).
I'm really struggling to get my head around exception handling. I've spent a lot of time on the web but not found anything along the lines of what I'm after.
We currently use a filter attribute that implements IExceptionFilter. We decorate a base controller class with this so all server side exceptions are nicely routed to an exception page that displays the error and performs logging.
I've started to use AJAX calls that return JSON data but when the server side implementation throws an error, the filter is fired but the page does not redirect to the Error page - it just stays on the page that called the AJAX method.
Is there any way to force the redirect on the server (e.g. a ASP.NET Server.Transfer or redirect?)
I've read that I must return a JSON object (wrapping the .NET Exception) and then redirect on the client, but then I can't guarantee the client will redirect... but then (although I'm probably doing something wrong) the server attempts to redirect but then gets an unauthorised exception (the base controller is secured but the Exception controller is not as it does not inherit from this)
Has anybody please got a simple example (.NET and jQuery code). I feel like I'm randomly trying things in the hope it will work
Exception Filter so far...
public class HandleExceptionAttribute : FilterAttribute, IExceptionFilter
{
#region IExceptionFilter Members
public void OnException(ExceptionContext filterContext)
{
if (filterContext.ExceptionHandled)
{
return;
}
filterContext.Controller.TempData[CommonLookup.ExceptionObject] = filterContext.Exception;
if (filterContext.HttpContext.Request.IsAjaxRequest())
{
filterContext.Result = AjaxException(filterContext.Exception.Message, filterContext);
}
else
{
//Redirect to global handler
filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new { controller = AvailableControllers.Exception, action = AvailableActions.HandleException }));
filterContext.ExceptionHandled = true;
filterContext.HttpContext.Response.Clear();
}
}
#endregion
private JsonResult AjaxException(string message, ExceptionContext filterContext)
{
if (string.IsNullOrEmpty(message))
{
message = "Server error"; //TODO: Replace with better message
}
filterContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
filterContext.HttpContext.Response.TrySkipIisCustomErrors = true; //Needed for IIS7.0
return new JsonResult
{
Data = new { ErrorMessage = message },
ContentEncoding = Encoding.UTF8,
};
}
}
I use the OnFailure hanlder in Ajax.Beginform(). The client-side failure handler can redirect by setting window.location (among a number of other options.) This will work in 99% of modern browsers- if the browser supports AJAX it should support this.

Having problems with ASP.NET MVC and StructureMap

I've got StructureMap working fine on my machine. Everything works great ... until I request a resource that doesn't exist. Instead of a 404, i get a 500 error.
eg. http://localhost:6969/lkfhklsfhskdfksdf
Checking the net, i was told to fix my structuremap controller class. Did that and joy! i now get the -original default 404 yellow screen page-. Ok, that's better than my 500 error page.
BUT, i want it to go to my custom 404 page :( If i call a bad action on a legit controller, i get my custom 404 page.
In my global.asax i have my custom routes, then the default, then finally the 404 route:
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Post", action = "Index", id = "" } // Parameter defaults
);
// Invalid/Unknown route.
routes.MapRoute(
"404-ResourceNotFound",
"{*url}",
new { controller = "StaticContent", action = "ResourceNotFound" }
);
Here's my structuremap controller code:
public class StructureMapControllerFactory: DefaultControllerFactory {
protected override IController GetControllerInstance(Type controllerType) {
if (controllerType != null) {
return ObjectFactory.GetInstance(controllerType) as Controller;
return base.GetControllerInstance(controllerType);
}
}
Any ideas? is there some way i could somehow get the structure map controller factory to bubble back into the global.asax routes list? or have i done something really bad and need to fix up some other stuff.
cheers!
mmm... seems like it might be an exception thing. like the way MVC is designed to handle the 404 errors via exceptions.
here is my code:
public class StructureMapControllerFactory : DefaultControllerFactory
{
protected override IController GetControllerInstance(Type controllerType)
{
IController result = null;
try
{
result = ObjectFactory.GetInstance(controllerType) as Controller;
}
catch (StructureMapException)
{
System.Diagnostics.Debug.WriteLine(ObjectFactory.WhatDoIHave());
throw;
}
return result;
}
}
.. you may have even had this and changed it. If not, try it and see if there is a difference. I dont suspect there will be.
Maybe just try breaking into that override and seeing what exceptions are being thrown.
(side note: its weird how i keep stumbling on your questions Krome. What r u working on?)
EDIT: I tried the garb request and got the same exception. So i updated my class like you did.
My new class:
public class StructureMapControllerFactory : DefaultControllerFactory
{
protected override IController GetControllerInstance(Type controllerType)
{
if (controllerType == null)
return base.GetControllerInstance(controllerType);
IController result = null;
try
{
result = ObjectFactory.GetInstance(controllerType) as Controller;
}
catch (StructureMapException)
{
System.Diagnostics.Debug.WriteLine(ObjectFactory.WhatDoIHave());
throw;
}
return result;
}
}
..this seems to give me back the 404 like it should.. but i never get the custom error pages in development (locally).. i have to wait till i publish before i get those. Are you used to seeing the custom error pages in dev?

Logging errors in ASP.NET MVC

I'm currently using log4net in my ASP.NET MVC application to log exceptions. The way I'm doing this is by having all my controllers inherit from a BaseController class. In the BaseController's OnActionExecuting event, I log any exceptions that may have occurred:
protected override void OnActionExecuted(ActionExecutedContext filterContext)
{
// Log any exceptions
ILog log = LogManager.GetLogger(filterContext.Controller.GetType());
if (filterContext.Exception != null)
{
log.Error("Unhandled exception: " + filterContext.Exception.Message +
". Stack trace: " + filterContext.Exception.StackTrace,
filterContext.Exception);
}
}
This works great if an unhandled exception occurred during a controller action.
As for 404 errors, I have a custom error set up in my web.config like so:
<customErrors mode="On">
<error statusCode="404" redirect="~/page-not-found"/>
</customErrors>
And in the controller action that handles the "page-not-found" url, I log the original url being requested:
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult PageNotFound()
{
log.Warn("404 page not found - " + Utils.SafeString(Request.QueryString["aspxerrorpath"]));
return View();
}
And this also works.
The problem that I'm having is how to log errors that are on the .aspx pages themselves. Let's say I have a compilation error on one of the pages or some inline code that will throw an exception:
<% ThisIsNotAValidFunction(); %>
<% throw new Exception("help!"); %>
It appears that the HandleError attribute is correctly rerouting this to my Error.aspx page in the Shared folder, but it is definitely not being caught by my BaseController's OnActionExecuted method. I was thinking I could maybe put the logging code on the Error.aspx page itself, but I'm unsure of how to retrieve the error information at that level.
I would consider simplifying your web application by plugging in Elmah.
You add the Elmah assembly to your project and then configure your web.config. It will then log exceptions created at controller or page level. It can be configured to log to various different places (like SQL Server, Email etc). It also provides a web frontend, so that you can browse through the log of exceptions.
Its the first thing I add to any asp.net mvc app I create.
I still use log4net, but I tend to use it for logging debug/info, and leave all exceptions to Elmah.
You can also find more information in the question How do you log errors (Exceptions) in your ASP.NET apps?.
You can hook into the OnError event in the Global.asax.
Something like this:
/// <summary>
/// Handles the Error event of the Application control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
protected void Application_Error(object sender, EventArgs e)
{
if (Server != null)
{
Exception ex = Server.GetLastError();
if (Response.StatusCode != 404 )
{
Logging.Error("Caught in Global.asax", ex);
}
}
}
MVC3
Create Attribute that inherits from HandleErrorInfoAttribute and includes your choice of logging
public class ErrorLoggerAttribute : HandleErrorAttribute
{
public override void OnException(ExceptionContext filterContext)
{
LogError(filterContext);
base.OnException(filterContext);
}
public void LogError(ExceptionContext filterContext)
{
// You could use any logging approach here
StringBuilder builder = new StringBuilder();
builder
.AppendLine("----------")
.AppendLine(DateTime.Now.ToString())
.AppendFormat("Source:\t{0}", filterContext.Exception.Source)
.AppendLine()
.AppendFormat("Target:\t{0}", filterContext.Exception.TargetSite)
.AppendLine()
.AppendFormat("Type:\t{0}", filterContext.Exception.GetType().Name)
.AppendLine()
.AppendFormat("Message:\t{0}", filterContext.Exception.Message)
.AppendLine()
.AppendFormat("Stack:\t{0}", filterContext.Exception.StackTrace)
.AppendLine();
string filePath = filterContext.HttpContext.Server.MapPath("~/App_Data/Error.log");
using(StreamWriter writer = File.AppendText(filePath))
{
writer.Write(builder.ToString());
writer.Flush();
}
}
Place attribute in Global.asax RegisterGlobalFilters
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
// filters.Add(new HandleErrorAttribute());
filters.Add(new ErrorLoggerAttribute());
}
Have you thought about extending the HandleError attribute? Also, Scott has a good blog post about filter interceptors on controllers/ actions here.
The Error.aspx view is defined like this:
namespace MvcApplication1.Views.Shared
{
public partial class Error : ViewPage<HandleErrorInfo>
{
}
}
The HandleErrorInfo has three properties:
string ActionName
string ControllerName
Exception Exception
You should be able to access HandleErrorInfo and therefore the Exception within the view.
You can try to examine HttpContext.Error, but I am not sure on this.

Resources