问题
An exception is thrown when I call Html.Action
from a view when the controller is decorated with the OutputCache
attribute. But when I remove the attribute from the controller everything works as expected.
I do not want to remove the OutputCache-attribute and I don't understand how the attribute is responsible for throwing the exception. How do I solve this problem?
Controller:
[OutputCache(Location = OutputCacheLocation.None, NoStore = true)]
public class TestController : Controller
{
public PartialViewResult Test()
{
Debug.WriteLine("test");
return PartialView();
}
}
View:
<div>
<!-- Tab 1 -->
@Html.Action("Test")
</div>
Exception:
{"Error executing child request for handler 'System.Web.Mvc.HttpHandlerUtil+ServerExecuteHttpHandlerAsyncWrapper'."}
InnerException
{"Child actions are not allowed to perform redirect actions."}
Update I only get the exception when I try to disable the outputcache. Either by adding the above attribute or setting the duration to 0.
回答1:
There are other ways to disable the cache too, go to
Global.asax.cs
file and add the following code,
protected void Application_BeginRequest()
{
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetExpires(DateTime.UtcNow.AddHours(-1));
Response.Cache.SetNoStore();
}
Now you don't need to add the [OutputCache]
attribute now. Let me know if it worked ! Cheers
回答2:
The outputcache attribute generated a hidden exception because the Duration property was not specified. However the duration cannot be 0 so that made the OutputCache attribute not very usefull for me. I decided to create my own NoCache attribute to take care of the work. (See code below)
Using this attribute instead of the OutputCacheAttribute solved my problem.
using System;
using System.Web;
using System.Web.Mvc;
namespace Cormel.QIC.WebClient.Infrastructure
{
public class NoCacheAttribute : ActionFilterAttribute
{
public override void OnResultExecuting(ResultExecutingContext filterContext)
{
filterContext.HttpContext.Response.Cache.SetExpires(DateTime.UtcNow.AddDays(-1));
filterContext.HttpContext.Response.Cache.SetValidUntilExpires(false);
filterContext.HttpContext.Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
filterContext.HttpContext.Response.Cache.SetCacheability(HttpCacheability.NoCache);
filterContext.HttpContext.Response.Cache.SetNoStore();
base.OnResultExecuting(filterContext);
}
}
}
来源:https://stackoverflow.com/questions/18760689/exception-on-use-of-html-action-when-controller-is-decorated-with-outputcache-at