如果你使用生活方式perwebrequest,你需要確保HttpContext不會在整個請求中重新創建。如果是,那麼你需要傳遞HttpContext.Items,因爲Castle http模塊使用它來跟蹤組件。
例如
改變了這個:
public CapturedViewResult Capture(ControllerContext controllerContext, Func<ActionResult> action)
{
CapturedViewResult capturedViewResult = new CapturedViewResult();
HttpContext currentContext = HttpContext.Current;
using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture))
{
HttpResponse response = new HttpResponse(stringWriter);
HttpContext context = new HttpContext(currentContext.Request, response) { User = currentContext.User };
context.Items["LocalizationContext"] = currentContext.Items["LocalizationContext"];
HttpContext.Current = context;
ViewResult result = action.Invoke() as ViewResult;
if (result != null)
{
capturedViewResult.ViewName = result.ViewName;
result.ExecuteResult(controllerContext);
}
else
{
throw new ArgumentException("Supplied controller action method did not return a ViewResult", "action");
}
HttpContext.Current = currentContext;
capturedViewResult.CapturedHtml = stringWriter.ToString();
}
return capturedViewResult;
}
要這樣:
public CapturedViewResult Capture(ControllerContext controllerContext, Func<ActionResult> action)
{
var capturedViewResult = new CapturedViewResult();
var currentContext = HttpContext.Current;
using (var stringWriter = new StringWriter(CultureInfo.InvariantCulture))
{
var response = new HttpResponse(stringWriter);
var context = new HttpContext(currentContext.Request, response) { User = currentContext.User };
foreach (var key in currentContext.Items.Keys)
{
context.Items.Add(key, currentContext.Items[key]);
}
HttpContext.Current = context;
var result = action.Invoke() as ViewResult;
if (result != null)
{
capturedViewResult.ViewName = result.ViewName;
result.ExecuteResult(controllerContext);
}
else
{
throw new ArgumentException("Supplied controller action method did not return a ViewResult", "action");
}
foreach (var key in context.Items.Keys)
{
currentContext.Items[key] = context.Items[key];
}
HttpContext.Current = currentContext;
capturedViewResult.CapturedHtml = stringWriter.ToString();
}
return capturedViewResult;
}
你已經註冊的溫莎HTTP模塊? – Nexus