gpt4 book ai didi

asp.net - 如何在自定义错误页面中访问 HTTP StatusDescription

转载 作者:行者123 更新时间:2023-12-04 12:51:36 28 4
gpt4 key购买 nike

当操作 (asp.net mvc 5) 在数据库中找不到某些内容时,用户必须看到带有简短自定义错误消息的页面,例如"Invoice 5 does not exist" .此外,响应必须有 404 HTTP 代码。
另一个例子:当 Action 被不正确地调用时,用户必须看到例如"Parameter 'invoiceId' is required" .此外,响应必须有 400 HTTP 代码。
我尝试将自定义消息存储在 HTTP 状态描述中并在自定义错误页面中显示它们。有两种方法(afaik):
一种

mvc action:
return HttpNotFound("Invoice 5 does not exist"); OR
return new HttpStatusCodeResult(HttpStatusCode.BadRequest, "Parameter 'invoiceId' is required");

web.config:
<httpErrors errorMode="Custom">
<remove statusCode="404" />
<error statusCode="404" path="/Error/NotFound" responseMode="ExecuteURL" />
<remove statusCode="400" />
<error statusCode="400" path="/Error/BadRequest" responseMode="ExecuteURL" />
</httpErrors>
mvc action:
throw new HttpException(404, "Invoice 5 does not exist"); OR
throw new HttpException(400, "Parameter 'invoiceId' is required");

web.config:
<customErrors mode="On">
<error statusCode="404" redirect="~/Error/NotFound" />
<error statusCode="400" redirect="~/Error/BadRequest" />
</customErrors>
无论哪种方式,如何在自定义页面中显示 HTTP 状态描述?如何在 NotFound/BadRequest 操作或 View 中访问它?
如果这是不可能的,那么 4xx 响应如何包含数据驱动的消息,很好地呈现给用户?
更新:
我沉迷于使用配置,但似乎不可能将自定义字符串推送到 web.config 中声明的错误页面。 @Carl 和 @V2Solutions 都只回答了我的后备问题(从“如果这是不可能的……”开始)。我会这样总结他们的方法:
C(@卡尔)

Don't use web.config or HttpStatusCodeResult.

Throw exceptions, catch them in Application_Error and render custom error pages programmatically.


D (@V2Solutions)

Don't use web.config, exceptions, or HttpStatusCodeResult.

Set the status code/description directly in the Response and return whatever view you like.

最佳答案

创建一个 ErrorController - 这允许您定制最终用户的错误页面和状态代码。每个操作结果都接受一个异常,您可以将其添加到 global.asax 的 application_error 方法中的路由数据中。它不必是异常对象,它可以是您喜欢的任何东西——只需将它添加到 application_error 中的路由数据即可。

[AllowAnonymous]
public class ErrorController : Controller
{
public ActionResult PageNotFound(Exception ex)
{
Response.StatusCode = 404;
return View("Error", ex);
}

public ActionResult ServerError(Exception ex)
{
Response.StatusCode = 500;
return View("Error", ex);
}

public ActionResult UnauthorisedRequest(Exception ex)
{
Response.StatusCode = 403;
return View("Error", ex);
}

//Any other errors you want to specifically handle here.

public ActionResult CatchAllUrls()
{
//throwing an exception here pushes the error through the Application_Error method for centralised handling/logging
throw new HttpException(404, "The requested url " + Request.Url.ToString() + " was not found");
}
}

您的错误 View :
@model Exception
@{
ViewBag.Title = "Error";
}

<h2>Error</h2>

@Model.Message

添加一个路由以将所有 url 捕获到路由配置的末尾 - 这将捕获通过匹配现有路由尚未捕获的所有 404:
routes.MapRoute("CatchAllUrls", "{*url}", new { controller = "Error", action = "CatchAllUrls" });

在您的 global.asax 中:
protected void Application_Error(object sender, EventArgs e)
{
Exception exception = Server.GetLastError();

//Error logging omitted

HttpException httpException = exception as HttpException;
RouteData routeData = new RouteData();
IController errorController = new Controllers.ErrorController();
routeData.Values.Add("controller", "Error");
routeData.Values.Add("area", "");
routeData.Values.Add("ex", exception);

if (httpException != null)
{
//this is a basic example of how you can choose to handle your errors based on http status codes.
switch (httpException.GetHttpCode())
{
case 404:
Response.Clear();

// page not found
routeData.Values.Add("action", "PageNotFound");

Server.ClearError();
// Call the controller with the route
errorController.Execute(new RequestContext(new HttpContextWrapper(Context), routeData));

break;
case 500:
// server error
routeData.Values.Add("action", "ServerError");

Server.ClearError();
// Call the controller with the route
errorController.Execute(new RequestContext(new HttpContextWrapper(Context), routeData));
break;
case 403:
// server error
routeData.Values.Add("action", "UnauthorisedRequest");

Server.ClearError();
// Call the controller with the route
errorController.Execute(new RequestContext(new HttpContextWrapper(Context), routeData));
break;
//add cases for other http errors you want to handle, otherwise HTTP500 will be returned as the default.
default:
// server error
routeData.Values.Add("action", "ServerError");

Server.ClearError();
// Call the controller with the route
errorController.Execute(new RequestContext(new HttpContextWrapper(Context), routeData));
break;
}
}
//All other exceptions should result in a 500 error as they are issues with unhandled exceptions in the code
else
{
routeData.Values.Add("action", "ServerError");
Server.ClearError();
// Call the controller with the route
errorController.Execute(new RequestContext(new HttpContextWrapper(Context), routeData));
}
}

然后当你扔
throw new HttpException(404, "Invoice 5 does not exist");

您的消息将被传递并显示给用户。此时可以指定要使用的状态代码,并扩展 application_error 中的 switch 语句。

关于asp.net - 如何在自定义错误页面中访问 HTTP StatusDescription,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25887507/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com