如果您不想添加 HttpModule
在 web.config 中
<system.web>
<customErrors mode="On" defaultRedirect="~/MyController/MyErrorAction/" redirectMode="ResponseRedirect">
<error statusCode="401" redirect="~/MyController/MyErrorAction/" />
</customErrors>
在 global.asax.cs
protected void Application_EndRequest(object sender, EventArgs e)
{
HttpApplication application = (HttpApplication)sender;
if (application.Response.StatusCode != 401 || !application.Request.IsAuthenticated) return;
application.Response.ClearContent();
//You can replace the piece below is to redirect using MVC, or your can replace all this with application.Server.Execute(yourPage);
IController errorController = new SharedController();
var rd = new RouteData();
rd.Values.Add("controller", "MyController");
rd.Values.Add("action", "MyErrorAction");
rd.Values.Add("value", "You or your user group do not have permissions to use the address: " + Request.Url.PathAndQuery);
errorController.Execute(new RequestContext(new HttpContextWrapper(Context), rd));
HttpContext.Current.Server.ClearError();
}