gpt4 book ai didi

c# - 如何从 ASP.NET MVC 中的 HttpModule 执行 Controller 操作?

转载 作者:太空宇宙 更新时间:2023-11-03 18:15:34 25 4
gpt4 key购买 nike

我有以下 IHttpModule,我正在尝试找出如何从 Controller 针对给定的绝对或相对 URL 执行操作。

public class CustomErrorHandlingModule : IHttpModule
{
#region Implementation of IHttpModule

public void Init(HttpApplication context)
{
context.Error += (sender, e) =>
OnError(new HttpContextWrapper(((HttpApplication)sender).Context));
}

public void Dispose()
{}

public void OnError(HttpContextBase context)
{
// Determine error resource to display, based on HttpStatus code, etc.
// For brevity, i'll hardcode it for this SO question.
const string errorPage = @"/Error/NotFound";

// Now somehow execute the correct controller for that route.
// Return the html response.
}
}

如何做到这一点?

最佳答案

沿线的东西应该做的工作:

public void OnError(HttpContextBase context)
{
context.ClearError();
context.Response.StatusCode = 404;

var rd = new RouteData();
rd.Values["controller"] = "error";
rd.Values["action"] = "notfound";
IController controller = new ErrorController();
var rc = new RequestContext(context, rd);
controller.Execute(rc);
}

您可能还会发现以下 related answer有用。

关于c# - 如何从 ASP.NET MVC 中的 HttpModule 执行 Controller 操作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6972521/

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