2

I'm doing donut caching with the MVCDonutCaching library.

Background to donut caching using this library:
The way it works, is you can cache a view, but exclude part of it from being cached, i.e. the "donut hole". You do this by having the uncachable stuff as a partial view, which is rendered by a child action. Then in the view you call that child action Html.RenderAction(.... This way everything but that child action will be cached.

Problem:
I need to cache a view, which contains a form. Problem is the form includes an AntiForgeryToken, which obviously should not be cached.

An obvious solution is to make that form a "donut hole", and render it via a child action. But, it needs complex viewmodel data, and child actions ony accept primitive types as arguments, otherwise I get serialization errors.

What is a good way around this?

4

1 回答 1

2

找到了办法。不确定它是否是最佳的,但它有效。

我没有将表单设为“甜甜圈洞”,而是将防伪令牌本身设为甜甜圈洞。

[ChildActionOnly]                
public virtual ContentResult GetAntiForgeryToken() {
  using (var viewPage = new ViewPage()) {
    var htmlHelper = new HtmlHelper(new ViewContext(), viewPage);
    var token = htmlHelper.AntiForgeryToken();
    return Content(token.ToHtmlString());
  }
}

这需要创建一个虚拟 HtmlHelper,然后手动创建令牌。

于 2015-05-21T18:09:13.280 回答