Error Handling Not working ASP .NET MVC - asp.net-mvc

I have created a new MVC Application in VS2010 straight out the box. In the Home Controller I have ther following:
[HandleError(View = "Error")]
public ActionResult Index()
{
int num1 = 0;
int num2 = 5;
int result = num2 / num1;
return View();
}
This creates an error and a debug pop up and then if I continue a yellow screen. I cannot get it to redirect to the Error.aspx page. I have the web.config like this:
<customErrors mode="On" defaultRedirect="~/Error.aspx">
</customErrors>
but it will not redirect to the correct error page despite being a brand new project. How do I configure this to work please????
thanks

This is discussed in the MVC overview tutorials. The behaviour of IIS errors is dependent on your version of IIS.
Using ASP.NET MVC with Different Versions of IIS (C#)

If I try to replicate this I get redirected to the default error view within the Shared view folder - it looks like MVC overrides any setting made to the defaultRedirect attribute in the web.config.
In your web.config you are trying to redirect to a physical aspx page. The HandleError attribute on your action will attempt to find a view named Error first within your specific view folder, moving on to the shared view folder. Just pick one or the other and you should be fine.

Try this blog post: http://msnetprogrammer.net/blog/post/HandleError-attribute-%28MVC%29.aspx
Also the default View name is Error so you technically can just have [HandleError]

Related

How to direct to an .aspx web form from a controller (MVC 5 framework)?

I have a MVC project which needs to incorporate SSRS reports as a part of the application. I've not done this before so I read up a couple of blogs, msdn pages etc. But I haven't come across a concrete solution yet.
Here's my code for the controller
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace AppName.Controllers
{
public class ReportsController : Controller
{
//
// GET: /Reports/
public ActionResult Index()
{
var reportParameters = new Dictionary<string, string>();
reportParameters.Add("First_Name", "TEST");
Session["reportParameters"] = reportParameters;
return Redirect("../Views/Reports/Index.aspx");
}
}
}
The last line 'return Redirect' does not redirect to the desired page , instead it gives me a 'can't find the page' error and the link displayed is as follows:
"/localhost:port#/Error/PageNotFound?aspxerrorpath=/Views/Reports/Index.aspx"
I have even tried 'RedirectRoute' and 'RedirectToAction', but none of them work. I am using a web form instead of an MVC view because that's what is presribed by many SSRS tutorials in order to achieve what I want. I know the redirect line has worked in the past for most folks. I'm surely missing something here. Any help would be greatly appreciated!
Thanks,
H
There is just a little tweak to have it working: instead of using a relative URL, do use an URL relative to the application root ~, like this:
return Redirect("~/Views/Reports/Index.aspx");
This will generate the current redirect URL.
EDIT
There can be a second problem in this case. The Views folder is somewhat special, because it has its own web.config which can make it impossible to get the files inside it. So you also need to move your .aspx page to somewhere else and update the Redirect accordingly.
To be more precise, if you look inside the web.config of your Views folder you'll find this:
<system.web>
<httpHandlers>
<add path="*" verb="*" type="System.Web.HttpNotFoundHandler"/>
</httpHandlers>
which means that any request to this folder will be handled with the HttpNotFoundHandler, thus you'll get the "not found" message.

How can I make an error page appear in my MVC application?

Currently I am getting error pages like this:
Server Error in '/' Application.
The partial view 'obj' was not found or no view engine supports the searched locations. The following locations were searched:
Is there a way that I can just return a plain error page to my users when my code has a problem?
You can define an error page in your web.config
http://www.aspdev.org/articles/web.config/
You should add [HandleError] attribute on top of your controller class. In your web.config add or change <customErrors> to <customErrors mode="on" />.
Also, here is a great article about different filters in MVC. One of the attributes covered is HandleError and it shows how to show your users plain text error messages.
http://blogs.msdn.com/b/gduthie/archive/2011/03/17/get-to-know-action-filters-in-asp-net-mvc-3-using-handleerror.aspx
Regards,
Huske
Following links will give you valuable insight on using custom error pages in asp.net mvc
ASP.NET MVC HandleError
ASP.NET MVC 404 Error Handling
1.You can use OnError method in global.asax
2.You can use ErrorHandler attribute and put it on controller or action.
3.You can use GlobalFilters to add error handling to all controllers. This is recommended way and alternative to global.asax
4.You can configure error handling in web.config.

error running asp.net mvc 2 project out of the box in vs 2010

i created a new solution and it builds fine targeting framework 4.0 but when i run it, my browser comes up saying:
The resource cannot be found.
Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.
Requested URL: /
any ideas on how to debug this?
Try adding the default.aspx page that comes with the asp.net mvc 1.0 project template. I had a similar issue running mvc 2 out of the box on a computer with IIS 5 (XP), and that did the trick.
Default.aspx:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="YourNamespace.Website.Default" %>
<%-- Please do not delete this file. It is used to ensure that ASP.NET MVC is activated by IIS when a user makes a "/" request to the server. --%>
Default.aspx.cs:
using System.Web;
using System.Web.Mvc;
using System.Web.UI;
namespace YourNamespace.Website
{
public partial class Default : Page
{
public void Page_Load(object sender, System.EventArgs e)
{
// Change the current path so that the Routing handler can correctly interpret
// the request, then restore the original path so that the OutputCache module
// can correctly process the response (if caching is enabled).
string originalPath = Request.Path;
HttpContext.Current.RewritePath(Request.ApplicationPath, false);
IHttpHandler httpHandler = new MvcHttpHandler();
httpHandler.ProcessRequest(HttpContext.Current);
HttpContext.Current.RewritePath(originalPath, false);
}
}
}
You don't need to add the default.aspx page described above.
The browser will display this 404 message if you add and run a new Empty ASP.NET MVC 2 application "out of the box".
This is because of the default route that is defined in global.asax.
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
You can see it is looking for a controller called Home and an action called Index.
When creating a new empty project it's left to you to create the Home controller and Index action (they are not there in an empty project), then create the view for the Index action too.
My guess is that you need to reregister or enable the framework under IIS.
Try running aspnet_regiis from the appropriate framework tree and / or make sure that the proper framework version is allowed under IIS web extensions.

ASP.net MVC [HandleError] not catching exceptions

In two different application, one a custom the other the sample MVC application you get with a new VS2008 MVC project, [HandleError] is not catching exceptions.
In the sample application I have:
[HandleError]
public class HomeController : Controller
{
public ActionResult Index()
{
ViewData["Message"] = "Welcome to ASP.NET MVC!";
throw new Exception();
return View();
}
public ActionResult About()
{
return View();
}
}
which is just the default controller with an exception being thrown for testing.
But it doesn't work. Instead of going to the default error.aspx page it shows the debug information in the browser.
The problem first cropped up in a custom application I'm working on which led me to test it with the sample application. Thinking it had something to do with changes I made in the custom application, I left the sample application completely unchanged with the exception (yuck) of the throw in the index method.
I'm stumped. What am I missing?
In Web.config, change customErrors:
<system.web>
<customErrors mode="On">
</customErrors>
If mode is either Off or RemoteOnly, then you will see the yellow screen of death instead of the custom error page. The reasoning is that developers usually want the more detailed information on the yellow screen of death.
Important: Be careful that your error page itself does not have an error on it!
If it does you'll end up with that ASP.NET custom error page and end up going round in circles and tearing your hair out. Just strip everything out of the page that could possibly cause an error and test it.
Also with respect to 'customErrors' being ON or OFF there are several contributing factors to whether or not the friendly error page (your Errors.aspx) page will be shown or not.
See this blog (except below)
HttpContext.IsCustomErrorEnabled - looks at three different sources
The web.config's <deployment> section's retail property. This is a
useful property to set when deploying
your application to a production
server. This overrides any other
settings for custom errors.
The web.config's <customErrors> section's mode property. This setting
indicates whether custom errors are
enabled at all, and if so whether they
are enabled only for remote requests.
The HttpRequest object's IsLocal property. If custom errors are enabled
only for remote requests, you need to
know whether the request is from a
remote computer.
The idea here is that you can have 'customErrors' turned OFF during development - when you do want to see the errors, and then enable it for production only.
This MSDN article discusses the attribute further.
Another reason for this problem may be ,
In Template MVC Application (generated by VS2008 / VS2008 Express) , Error.aspx (generated by VS) uses Master Page.
If Master Page access any ViewData it will throw null reference Exception , then the error.aspx won't be shown.
Use this Simple code as your Error.aspx , it will solve the problem, (along with CustomErrors=On )
<%# Page Language="C#" Inherits="System.Web.Mvc.ViewPage<System.Web.Mvc.HandleErrorInfo>" %>
<%= Model.Exception.Message %>
I have struggled with this as well and I believe I understand the problem now.
In short the requirements for having [HandleError] work as expected are:
You must enable custom errors in web.config AND you must also specify where your error view is in the <customErrors> tag.
Example:
<customErrors mode="On" defaultRedirect="Error" />
Leaving off the defaultRedirect="Error" part will instead yield a 500 error in the browser--NOT the ASP.NET error page (YSOD).
Also you do not have to be in Release mode. I tested this with a Debug build and it worked fine.
My environment was Visual Studio 2010 using .NET 4 and the standard, "ASP.NET MVC 2 Web Application" project template.
What confused me was the MSDN documentation for the HandleErrorAttribute Class. It doesn't explicitly say you must turn on custom errors in web.config. And I assumed all I needed was the [Handle Error] attribute.
There is some silly situation which once happened with me, so might be helpfull for someone.
Be sure that you've added <customErrors mode="On" /> to the correct web.config file.
Sometimes (especially, when you work with something like Resharper, and open your files with typing their name, but not via Solution Explorer), you can simply open a web.config either from Views folder or even from another project.
Watch out: in my case I was trying to get the HandleError attribute to catch an exception thrown inside the Controllers constructor! Of course it won't catch it. The HandleError attribute only catches exceptions thrown inside Controller actions. It's right there in the MSDN page (should've paid more attention to that):
Represents an attribute that is used to handle an exception that is
thrown by an action method.
Another thing that was happening is that the Controller's OnException(ExceptionContext exceptionContext) overridden method was never being called. Again: of course it would not be called since I was throwing an exception inside the Controller's constructor.
I spent 1 hour trying to figure this out. :o) Hope it helps the next soul...
As a hint: remember that the HandleError attribute only catches 500 errors. For the other ones you should declare the <customErrors> section in Web.config:
<customErrors mode="On">
<error statusCode="403" redirect="~/403" />
<error statusCode="404" redirect="~/404" />
</customErrors>

MVC View Problem

I have an mvc application running on IIS 7.0 on windows vista.The appication is redirecting to the proper controller and action.But i am getting an error saying view is not found in the path, when the view is present at the particular path.
Route is as shown below.
routes.MapRoute(
"Default", // Route name
"home/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = "" } // Parameter constraints
);
I am getting the error as The view 'Index' could not be located at these paths: ~/Views/Home/Index.aspx, ~/Views/Home/Index.ascx, ~/Views/Shared/Index.aspx, ~/Views/Shared/Index.ascx when i run the mvc application http://localhost/mvcsf/Home/
I had to reconfigure IIS to handle MVC apps. Check this one out as well:
MVC Config on IIS v6.0
Try something like this, it seems like it lies in the Windows features that comes with IIS 7 :
http://blogs.dovetailsoftware.com/blogs/kmiller/archive/2008/10/07/deploying-an-asp-net-mvc-web-application-to-iis7.aspx
The choice of view is defined by the controller. What does the home controller do for the Index action? If this is the vanilla site generated by the system, then it is expecting to find "~/Views/Home/Index.aspx", via the controller's action (below). So: does this index page exist?
public ActionResult Index()
{
ViewData["Title"] = "Home Page";
ViewData["Message"] = "Welcome to ASP.NET MVC!";
return View();
}
(the default view has the pattern {controller}/{action}; you can specify other views via overloads on View(...))

Resources