After browsing 100 of link for this topic I couldnt find solution to my problem. I am handling 404 custom error page manually like below
My below solution work when I type any wrong url in address bar and shows 404 error page rightly. But when I type http://localhost:57101/p/any
or http://localhost:57101/p/123
it shows webpage not available. for first one its the error of parameter id cannot contain null entry. Second one is the products id which is deleted so product is null, So I am throwing manual exceptions there.
My web.config setting is
<customErrors mode="On" redirectMode="ResponseRedirect">
</customErrors>
My code to handle 404 error
protected void Application_Error(Object sender, EventArgs e)
{
//LogException(Server.GetLastError());
try
{
var exception = Server.GetLastError();
LogException(exception);
var httpException = exception as HttpException;
Response.Clear();
Server.ClearError();
var routeData = new RouteData();
routeData.Values["controller"] = "Errors";
routeData.Values["action"] = "General";
routeData.Values["exception"] = exception;
Response.StatusCode = 500;
if (httpException != null)
{
Response.StatusCode = httpException.GetHttpCode();
switch (Response.StatusCode)
{
case 403:
routeData.Values["action"] = "Http403";
break;
case 404:
routeData.Values["action"] = "Http404";
break;
}
}
else
{
Response.StatusCode = 404;
routeData.Values["action"] = "Http404";
}
IController errorsController = new Nop.Web.Controllers.ErrorsController();
var rc = new RequestContext(new HttpContextWrapper(Context), routeData);
errorsController.Execute(rc);
}
catch { }
#endregion
//log error
}
Above code works when I try to browse any non existent route. But when I throw exception as below
My Errors controller is
public class ErrorsController : Controller
{
//
// GET: /Errors/
public ActionResult General(Exception exception)
{
Response.ContentType = "text/html";
Response.TrySkipIisCustomErrors = true;
return View();
}
public ActionResult Http404()
{
//return Content("Not found", "text/plain");
Response.ContentType = "text/html";
Response.TrySkipIisCustomErrors = true;
return View();
}
public ActionResult Http403()
{
Response.ContentType = "text/html";
Response.TrySkipIisCustomErrors = true;
return View();
}
}
public ActionResult Product(int productId)
{
var product = _productService.GetProductById(productId);
if(product==null)
throw new HttpException(404, "Product does not exists");
}
It shows "This webpage is not available".
Also I want to keep url as it is just like stackoverflow
does it.
Any help regarding this.