gpt4 book ai didi

c# - 不允许过滤

转载 作者:可可西里 更新时间:2023-11-01 09:04:08 24 4
gpt4 key购买 nike

我已经实现了一种操作方法来缩小 HTML,它给出了异常“不允许过滤”我已经搜索了互联网但找不到任何合适的解决方案。请指导我如何解决这个问题。我正在分享我的代码:

MinifyAttribute 类:

public class MinifyAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{

var request = filterContext.HttpContext.Request;
var response = filterContext.HttpContext.Response;

response.Filter = new Minify(response.Filter, s =>
{
s = Regex.Replace(s, @"\s+", " ");
s = Regex.Replace(s, @"\s*\n\s*", "\n");
s = Regex.Replace(s, @"\s*\>\s*\<\s*", "><");
s = Regex.Replace(s, @"<!--(.*?)-->", ""); //Remove comments

var firstEndBracketPosition = s.IndexOf(">");
if (firstEndBracketPosition >= 0)
{
s = s.Remove(firstEndBracketPosition, 1);
s = s.Insert(firstEndBracketPosition, ">");
}
return s;
}); // i'm getting exception here on this code block

}
}

缩小类

public class Minify : Stream
{
private Stream _shrink;
private Func<string, string> _filter;

public Minify(Stream shrink, Func<string, string> filter)
{
_shrink = shrink;
_filter = filter;
}


public override bool CanRead { get { return true; } }
public override bool CanSeek { get { return true; } }
public override bool CanWrite { get { return true; } }
public override void Flush() { _shrink.Flush(); }
public override long Length { get { return 0; } }
public override long Position { get; set; }
public override int Read(byte[] buffer, int offset, int count)
{
return _shrink.Read(buffer, offset, count);
}
public override long Seek(long offset, SeekOrigin origin)
{
return _shrink.Seek(offset, origin);
}
public override void SetLength(long value)
{
_shrink.SetLength(value);
}
public override void Close()
{
_shrink.Close();
}

public override void Write(byte[] buffer, int offset, int count)
{
// capture the data and convert to string
byte[] data = new byte[count];
Buffer.BlockCopy(buffer, offset, data, 0, count);
string s = Encoding.Default.GetString(buffer);

// filter the string
s = _filter(s);

// write the data to stream
byte[] outdata = Encoding.Default.GetBytes(s);
_shrink.Write(outdata, 0, outdata.GetLength(0));
}


}

我在 Controller 上调用这个方法并得到异常

最佳答案

尝试在应用过滤器之前添加空检查:

public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var response = filterContext.HttpContext.Response;

if (response.Filter == null) return; // <-----

response.Filter = new YourFilter(response.Filter);
}

关于c# - 不允许过滤,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23708181/

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