如何从 ASP.NET MVC 中的 HttpModule 执行控制器操作?
我有以下 IHttpModule
,我试图找出如何从给定绝对或相对 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.
}
}
这怎么能做到呢?
I've got the following IHttpModule
and I'm trying to figure out how to execute an action from a controller for a given absolute or relative 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.
}
}
How can this be done?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
类似的东西应该可以完成这项工作:
您可能还会发现以下 相关答案有用。
Something along the lines should do the job:
You might also find the following related answer useful.
我认为您需要使用 HttpContext.Current.RewritePath
这可以让您更改要使用的文件的路径。这就是 MVC 2 项目中创建的
default.aspx
的作用。我使用它的方式与您大致相同,在没有 302 的情况下进行错误处理,但现在无法访问我的代码。我会在周一发布一些代码。
I think you need to use
HttpContext.Current.RewritePath
This lets you change the path for the file you want to use. It's what the
default.aspx
created in MVC 2 projects does.I've used it in much the same way you are, to do error handling without a 302 but can't get to my code right now. I'll post some code on Monday.
您可以使用 HttpContext:
You can using HttpContext:
您可以使用它让框架使用路由和所有组件执行该路径的代码:
理想情况下,此时请求处理已完成。如果情况并非如此,并且请求沿着 asp.net http 管道进一步处理,则使用此方法在此时停止请求,并告诉 asp.net 我们已完成此请求:
我不确定是否上下文有应用程序(我现在不在 VS 附近),但如果需要,可以使用它来停止此模块中的请求。
Hi use this to let the framework execute the code for that path using the routing and all the components :
And ideally the request processing is completer at this point. If this is not the case and if the request is further processed along the asp.net http pipeline, then use this to stop the request at this point, and tell asp.net that we're done with this request :
Im not sure if the context has the Application (im not near VS now) but use it to stop the request in this module if needed.