My .net mvc application is running on IIS, in release mode, when I try to access a page, it shows "An error occurred while processing your request."
After I remove the role from AuthorizeUser as shown below, I can access the page. Can anyone give advice?
Fail:
[AuthorizeUser(Roles = Role.User1)]
public class TestController : Controller
OK:
[AuthorizeUser]
public class TestController : Controller
Looks like your AD does not have roles User1.
Please go through the following link to get a better idea.
https://learn.microsoft.com/en-us/previous-versions/aspnet/web-frameworks/dd460317(v=vs.100)
Finally I solved it by adding these lines into web.config:
<modules>
<remove name="RoleManager" />
</modules>
Related
I am a newbie to MVC.
I am trying to create a custom error page to show when the user is looking for an unavailable resource. I followed a few articles and was able to show a custom error page.
ASP.NET MVC 404 Error Handling.
I have created an error Controller with 'NotFound404()' action method and view is created with the same name 'NotFound404.cshtml'.
public class ErrorController : Controller
{
// GET: Error
public ActionResult NotFound404()
{
return View();
}
}
Web.config
<system.web>
<customErrors mode="On">
<error statusCode="404" redirect="~/Error/NotFound404"/>
</customErrors>
</system.web>
When I try to access any unknown resource, I can see the notfound404. But when I inspect URL it shows as 'http://localhost:xyzw/Error/NotFound404?aspxerrorpath=/New'.
Why do i get such weird URL? and I am not using any aspx pages but it
shows aspx in the URL. HTTP status under F12-Developer tools- Network -
shows 200 which isn't correct. How do I rectify this?
And when I tried to access any static HTML page instead of a new controller/ action-view
<system.web>
<customErrors mode="On">
<error statusCode="404" redirect="~/Shared/NotFound.html"/>
</customErrors>
</system.web>
404 Error occurs -- is this error because it is looking up for wrong path?
How do I fix these errors?
Please show a right way to configure these error handling strategies.
Thanks in advance.
I have a asp.net mvc application and everything seems to be working fine on my Development machine however when I try to deploy and run the application on a server it gives me the following error:
System.NullReferenceException: Object reference not set to an instance of an object.
This happens on this line of code. All I am trying to do is set a value in the session.
I have this code inside a partial class of the Controller.
public partial class HomeController : BaseController
{
public ActionResult Index(string Value)
{
System.Web.HttpContext.Current.Session["Test"] = "world";
return View();
}
}
Thanks that led me to find solution here:
Solution 1 from ASP.NET MVC - Session is null worked for me.
"
Solution 1:
Link: HttpContext.Current.Session is null when routing requests
Got it. Quite stupid, actually. It worked after I removed & added the SessionStateModule like so:
<configuration>
...
<system.webServer>
...
<modules>
<remove name="Session" />
<add name="Session" type="System.Web.SessionState.SessionStateModule"/>
...
</modules>
</system.webServer>
</configuration>
Simply adding it won't work since "Session" should have already been defined in the machine.config.
Now, I wonder if that is the usual thing to do. It surely doesn't seem so since it seems so crude..."
I can't get ANY custom error pages to appear in IIS8.5!
When I run my MVC 5 app locally in Visual Studio, custom error pages are displayed. But when I deploy to IIS on my webserver, and navigate to the site sub-page with a 'bad URL' my custom 404 page should be displayed, but the default generic 404 page is shown instead.
Here is what I've done:
web.config
customError section has been deleted.
Added the following section
<system.webServer>
<httpErrors errorMode="Custom" existingResponse="Replace">
<remove statusCode="404" />
<remove statusCode="500" />
<error statusCode="404" responseMode="ExecuteURL" path="/Error/NotFound" />
<error statusCode="500" responseMode="ExecuteURL" path="/Error/ServerError" />
</httpErrors>
</system.webServer>
Controller
namespace MyApp.Controllers
{
[Authorize(Roles = "MyRole")]
public class ErrorController : Controller
{
[AllowAnonymous]
public ActionResult NotFound()
{
Response.StatusCode = 404;
return View();
}
[AllowAnonymous]
public ActionResult ServerError()
{
Response.StatusCode = 500;
return View();
}
}
}
Views
Very simple and straight forwards (not included here).
IIS
Verified the IIS Error Page feature is identical to what's in my config. A page for each error status code. Feature and Pages are set to 'custom'.
Checked Windows Features\Web Server (IIS)\Web Server\Common HTTP Features\HTTP Errors is installed.
Developer Tools
Navigating to a sub-page spelt incorrectly shows I'm getting a 404 Client Error.
Help
I've tries many things! Am I missing something? IIS environmental issue, i.e. a setting somewhere?
Custom errors work in my IDE but not on IIS. I've spent over a day on this! Read many pages, articles, and similar questions on SO.
After several days of investigating, finally found the issue.
In IIS, my website was residing as an Application under the Default Web Site, e.g. Default Web Site\MyDevSite. (All my dev sites are under the default web site).
When I moved the website to it's own IIS site, custom error pages are now being displayed!
If anyone knowns the reason why having an Application in IIS prevents custom error pages from being displayed, please add a comment here. It would be good to understand why this occurs.
I hope this helps somebody out. Had me going for quite a while.
How are you browsing IIS? If you're doing it from the same machine, then you aren't going to see your custom error pages, because the customErrors section will default to using RemoteOnly if not specified.
the problem is with the path in web.config(path="/Error/NotFound"). the url path of NotFound page will be changed when you move your website under the Default Web Site. So, give the correct url of the page at path then it will work(this is worked for me).
I'm currently developing custom error pages in my error handling code for my MVC application. But I'm unclear as to which HTTP status codes I'm meant to cover.
Question: is there a typical list of HTTP status codes that should be catered for?
Alot articles which explain how to do MVC error handling and custom error pages but appear to only show several of the HTTP Status Codes: 403, 404, and 500 in their error handling code. What about HTTP Status Code: 408 as an example? Should this be covered? What about the tonne of other status codes - HTTP status codes on wiki
This may sound like a dumb question, but I really don't know the answer and can't find an information on this. Am I missing something here, i.e. should only a subset of status codes be covered?
If it helps, below is what I've done for my MVC error handling. This code (so far with the little testing that I've done) covers 404, and all 50x type exceptions:
1 In web.config, and entry for each HTTP status code I want to cover
<httpErrors errorMode="Custom" existingResponse="Replace" >
<remove statusCode="403" />
<remove statusCode="404" />
<remove statusCode="500" />
<error statusCode="403" responseMode="ExecuteURL" path="/Error/Forbidden" />
<error statusCode="404" responseMode="ExecuteURL" path="/Error/NotFound" />
<error statusCode="500" responseMode="ExecuteURL" path="/Error" />
</httpErrors>
2 An error controller
namespace MyApp.Controllers
{
public class ErrorController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult Forbidden()
{
return View();
}
public ActionResult NotFound()
{
return View();
}
3 User friendly error pages:
/Views/Shared/Index.cshtml
/Views/Shared/Forbidden.cshtml
/Views/Shared/NotFound.cshtml
4 ELMAH for logging
Further findings at 2 Nov 2015
Something I've just discovered that has been staring me in the face which I've missed... In IIS, the default Error pages covered are:
401 – Unauthorized
403 – Forbidden
404 – Not Found
405 – Method Not Allowed
406 – Not Acceptable
412 – Precondition Failed
500 – Internal Server Error
501 – Not Implemented
502 – Bad Gateway
If this is good range Microsoft have set, then I will go by this as a guide going forwards!
There may be another way: this solution uses 1 custom-error page to handle all types (I think?)
[1]: Remove all 'customErrors' & 'httpErrors' from Web.config
[2]: Check 'App_Start/FilterConfig.cs' looks like this:
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
}
[3]: in 'Global.asax' add this method:
public void Application_Error(Object sender, EventArgs e)
{
Exception exception = Server.GetLastError();
Server.ClearError();
var routeData = new RouteData();
routeData.Values.Add("controller", "ErrorPage");
routeData.Values.Add("action", "Error");
routeData.Values.Add("exception", exception);
if (exception.GetType() == typeof(HttpException))
{
routeData.Values.Add("statusCode", ((HttpException)exception).GetHttpCode());
}
else
{
routeData.Values.Add("statusCode", 500);
}
Response.TrySkipIisCustomErrors = true;
IController controller = new ErrorPageController();
controller.Execute(new RequestContext(new HttpContextWrapper(Context), routeData));
Response.End();
}
[4]: Add 'Controllers/ErrorPageController.cs'
public class ErrorPageController : Controller
{
public ActionResult Error(int statusCode, Exception exception)
{
Response.StatusCode = statusCode;
ViewBag.StatusCode = statusCode + " Error";
return View();
}
}
[5]: in 'Views/Shared/Error.cshtml'
#model System.Web.Mvc.HandleErrorInfo
#{
ViewBag.Title = (!String.IsNullOrEmpty(ViewBag.StatusCode)) ? ViewBag.StatusCode : "500 Error";
}
<h1 class="error">#(!String.IsNullOrEmpty(ViewBag.StatusCode) ? ViewBag.StatusCode : "500 Error"):</h1>
//#Model.ActionName
//#Model.ContollerName
//#Model.Exception.Message
//#Model.Exception.StackTrace
An interesting question, IMHO.
These three errors (403, 404 and 500) are the most common errors that can happen to the real user accessing your site with a standard browser.
On other hand, the HTTP standard was written for both server and agent developers in order to define how both sides should operate. Naturally, the standard browsers like IE, Chrome, Firefox, etc. as well as the standard robots like Google or Bing bots correctly fulfill the requirements, but some proprietary written agent may send a malformed request, and the standard provides the set of codes the server should send in this situation. For example, if the Content-Length field is missed the server returns the error code 411. However, you shouldn't provide user-friendly pages for such a situation.
The code 408 (Request timeout) is explained in the standard as following:
"The client did not produce a request within the time that the server was prepared to wait. The client MAY repeat the request without modifications at any later time."
and it also not a case you should make user-friendly page for.
To make a long story short, don't worry :)
I'm trying to find out the answer also. My code looks scarily like yours. This is a great question with so few views, I've set a bounty on this question. I myself have handled the following codes so far:
<system.webServer>
<!-- Custom error pages -->
<httpErrors errorMode="Custom" existingResponse="Replace">
<!-- Redirect IIS 400 Bad Request responses to the error controllers bad request action. -->
<remove statusCode="400" />
<error statusCode="400" responseMode="ExecuteURL" path="/error/badrequest" />
<!-- Redirect IIS 401 Unauthorized responses to the error controllers unauthorized action. -->
<remove statusCode="401" />
<error statusCode="401" responseMode="ExecuteURL" path="/error/unauthorized" />
<!-- Redirect IIS 403.14 Forbidden responses to the error controllers not found action.
A 403.14 happens when navigating to an empty folder like /Content and directory browsing is turned off
See http://rehansaeed.co.uk/securing-the-aspnet-mvc-web-config/ and http://www.troyhunt.com/2014/09/solving-tyranny-of-http-403-responses.html -->
<error statusCode="403" subStatusCode="14" responseMode="ExecuteURL" path="/error/notfound" />
<!-- Redirect IIS 404 Not Found responses to the error controllers not found action. -->
<remove statusCode="404" />
<error statusCode="404" responseMode="ExecuteURL" path="/error/notfound" />
<!-- Redirect IIS 500 Internal Server Error responses to the error controllers internal server error action. -->
<remove statusCode="500" />
<error statusCode="500" responseMode="ExecuteURL" path="/error" />
</httpErrors>
</system.webServer>
My reasoning is as follows:
400 - Controllers have the BadRequest() method built in and you may want to return this when a parameter passed to the action is invalid.
401 - Applying the Authorize attribute to a controller or action causes a 401 Unauthorized response. Controllers also have the Unauthorized() method built in.
403.14 - Redirect these to 404 Not Found responses as a Forbidden is just plain wrong (See Securing your web.config and Troy Hunt's blog for more information).
404 - Thrown when the user browses to a page not found.
500 - Thrown when something goes catastrophically wrong.
Overall I feel you should handle those codes that you yourself are going to use. The problem is that IIS does all kinds of strange things and we need to handle some of it's incorrect or invalid responses such as the 403.14 I listed above.
Here is a complete list of IIS HTTP Status Codes and Sub-Status Codes which might be useful to our cause. I have a feeling the 403 Forbidden response should also be supported as it seems to be a fairly prominent response thrown by IIS.
One interesting thing I discovered while Googling is that navigating to:
yoursite/<script></script>
Returns a 500 Internal Server from IIS. I feel this should return a 404. The IIS error page does not tell us what the Sub-Status Code is and I would be interested to know how we can find out, so that we can redirect the 500.Something to a 404 Not Found page.
Here is a link to the GitHub page for the ASP.NET MVC Boilerplate project, for which I am doing this research and where you can look at my code.
Don't rely too much on http status codes.
I have worked with a few bad web developers over the last couple of years that have incorrectly used them in their responses.
I may look for codes within 200-299 for an indication of success.
I may look for codes >500 to indicate a server failure.
Beyond that, I use a selfish approach i.e. if you are making a request that your are expecting to have a package of data returned to you, then inspect the data. If there is no data or if the data is bad then I know for certain that there was a problem, because I didn't get what I needed to continue running my application in a nominal way.
I use google recaptcha plug-in for ASP.NET in my asp.net mvc site. It works fine when I run it from my local work station. But it is wired after I deploy it on the serve, it could load correctly but page will return 500 internal error when I submit the page with the recaptcha code. If I just leave it blank and submit the page, no error at all.
So, I think it may be brought by some connection issue between google service?
do anyone have some idea about the issue and have any resolution?
the code is quite simple, just set public/private keys in the web.config and use HTML.RAW(recaptcha.generator...) to render the component in the page.
The code is simple: in the view, just add
#Html.Raw(Html.GenerateCaptcha("captcha", "clean"))
And in the controller, just use
[HttpPost]
[RecaptchaControlMvc.CaptchaValidator]
public ActionResult ActionName(Model model, bool captchaValid)
{
if(captchaValid)
{
ModelState.AddErro("....");
}
}
web.config:
<appSettings>
<add key="ReCaptchaPrivateKey" value="**************" />
<add key="ReCaptchaPublicKey" value="***************" />
</appSettings>