2009-03-30 32 views
11

Có ai biết làm thế nào để có được RequestContext hiện tại từ sự kiện Application_Error trong global.asax ?? Vấn đề của tôi là tôi cần phải làm một chuyển hướng, và do đó cần phải có url được tạo ra bằng cách sử dụng UrlHelper - trong đó có RequestContext đã đề cập ở trên.Truy cập RequestContext từ global.asax

+1

câu trả lời này sẽ giúp bạn? http://stackoverflow.com/a/2032154/330606 –

Trả lời

11

Trong khi không có cách nào trực tiếp truy cập vào RequestContext, bạn có thể tạo một bản thân:

RequestContext context = new RequestContext(new HttpContextWrapper(HttpContext.Current), RouteTable.Routes.GetRouteData(new HttpContextWrapper(HttpContext.Current))) 

Vì vậy, các UrlHelper thể được xây dựng qua:

UrlHelper helper = new UrlHelper(new RequestContext(new HttpContextWrapper(HttpContext.Current), RouteTable.Routes.GetRouteData(new HttpContextWrapper(HttpContext.Current)))); 

Không đẹp, nhưng nó được công công việc hoàn thành.

+0

Bạn có thể truy cập vào RequestContext, vui lòng tham khảo câu trả lời của tôi. –

0

Tạo một HttpContextBase từ HttpContext hiện tại, và từ đó bạn có thể tạo một UrlHelper:

// Create Http Context Base from current Context 
var contextBase = new System.Web.HttpContextWrapper(System.Web.HttpContext.Current); 
// Get its request context 
System.Web.Routing.RequestContext requestContext = contextBase.Request.RequestContext; 
// Build url helper from request context 
var urlHelper = new System.Web.Mvc.UrlHelper(requestContext); 
7

Bạn có thể truy cập vào bối cảnh yêu cầu sử dụng

HttpContext.Current.Request.RequestContext 

Hoặc, nếu bạn đang ở trong Global.asax bạn có thể sử dụng

Context.Request.RequestContext 

trực tiếp.

Các vấn đề liên quan