gpt4 book ai didi

asp.net-mvc - MVC.net 禁用特定方法的属性

转载 作者:行者123 更新时间:2023-12-04 06:40:43 24 4
gpt4 key购买 nike

我的 BaseController 类上有一个操作过滤器属性:

<CompressFilter()> _
Public Class BaseController

因此,此过滤器适用于我的应用程序的所有 Controller 中的所有方法。
是否可以为某些特定方法禁用此过滤器?

最佳答案

如果您有权访问 CompressFilter 的代码,那就是。您可以添加第二个属性。例如 NoCompressAttribute。在 CompressFilter 的 OnActionExecuting 方法中,您将查看 ActionDescriptors,如果应用了 NoCompressAttribute,您将不会进行压缩。

编辑:这是代码

 public class CompressFilter : ActionFilterAttribute
{
public bool Compress { get; set; }
public CompressFilter()
{
Compress = true;
}

public CompressFilter(bool compress)
{
Compress = compress;
}

public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var compressAttribs = filterContext.ActionDescriptor.GetCustomAttributes(typeof(CompressFilter), true);
foreach (var item in compressAttribs)
{
if (!((CompressFilter)item).Compress)
{
return;
}
}

HttpRequestBase request = filterContext.HttpContext.Request;

string acceptEncoding = request.Headers["Accept-Encoding"];

if (string.IsNullOrEmpty(acceptEncoding)) return;

acceptEncoding = acceptEncoding.ToUpperInvariant();

HttpResponseBase response = filterContext.HttpContext.Response;

if (acceptEncoding.Contains("GZIP"))
{
response.AppendHeader("Content-encoding", "gzip");
response.Filter = new GZipStream(response.Filter, CompressionMode.Compress);
}
else if (acceptEncoding.Contains("DEFLATE"))
{
response.AppendHeader("Content-encoding", "deflate");
response.Filter = new DeflateStream(response.Filter, CompressionMode.Compress);
}
}
}

然后在您不希望压缩的操作上执行以下操作:
[CompressFilter(false)]
public virtual ActionResult Index()
{
}

希望有帮助

关于asp.net-mvc - MVC.net 禁用特定方法的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4284053/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com