在浏览了100个关于此主题的链接后,我无法找到问题的解决方案。我正在手动处理404自定义错误页面,如下所示
当我在地址栏中输入任何错误的网址并正确显示404错误页面时,我的下方解决方案正常工作。但是当我输入http://localhost:57101/p/any
或http://localhost:57101/p/123
时
它显示网页不可用。对于第一个,它的参数id的错误不能包含空条目。第二个是删除的产品ID,因此产品为空,所以我在那里抛出手动例外。
我的web.config设置为
<customErrors mode="On" redirectMode="ResponseRedirect">
</customErrors>
我处理404错误的代码
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
}
当我尝试浏览任何不存在的路线时,上面的代码有效。 但是当我抛出异常时如下
我的错误控制器是
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");
}
显示“此网页不可用”。
此外,我想保留网址,因为它就像stackoverflow
那样。
对此有任何帮助。