3

私は次のコントローラーを持っています:

[NoCache]
public class AccountController : Controller
{
    [Authorize(Roles = "admin,useradmin")]
    public ActionResult GetUserEntitlementReport(int? userId = null)
    {
        var byteArray = GenerateUserEntitlementReportWorkbook(allResults);

        return File(byteArray,
                System.Net.Mime.MediaTypeNames.Application.Octet,
                "UserEntitlementReport.xls");
    }
}

public class NoCache : ActionFilterAttribute
{
    public override void OnResultExecuting(ResultExecutingContext filterContext)
    {
        var response = filterContext.HttpContext.Response; 
        response.Cache.SetExpires(DateTime.UtcNow.AddDays(-1));
        response.Cache.SetValidUntilExpires(false);
        response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
        response.Cache.SetCacheability(HttpCacheability.NoCache);
        response.Cache.SetNoStore();
        base.OnResultExecuting(filterContext);
    }
}

ご覧のとおり、コントローラーは[NoCache]属性で装飾されています。

この属性がGetUserEntitlementReportアクションに適用されないようにする方法はありますか?

コントローラーレベルで属性を削除できることはわかっていますが、コントローラーには他の多くのアクションが含まれており、各アクションに属性を個別に適用する必要がないため、それは私のお気に入りのソリューションではありません。

4

3 に答える 3

4

コントローラー レベルで指定された NoCache をオプトアウトするために、個々のアクションで使用できる新しい属性を作成できます。

[AttributeUsage(AttributeTargets.Class |
                AttributeTargets.Method,
                AllowMultiple = false,
                Inherited = true)]
public sealed class AllowCache : Attribute { }

キャッシュを許可するアクションをマークします[AllowCache]

次に、属性が存在しないNoCacheAttribute場合にのみキャッシュを無効にするためのコードでAllowCache

public class NoCacheAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        base.OnActionExecuting(filterContext);

        var actionDescriptor = filterContext.ActionDescriptor;
        bool allowCaching = actionDescriptor.IsDefined(typeof(AllowCache), true) ||
            actionDescriptor.ControllerDescriptor.IsDefined(typeof(AllowCache), true);

        if(!allowCaching)
        {
            //disable caching.
        }
    }
}
于 2013-02-12T16:32:40.007 に答える
0

これは、カスタム フィルター プロバイダーを実装して登録することで実現できます。まず、 FilterAttributeFilterProviderから派生させ、必要に応じて GetFilters をオーバーライドして NoCache 属性を削除します。

于 2013-02-12T15:53:31.387 に答える