gpt4 book ai didi

c# - IHttpAsyncHandler 和 Request.Filter

转载 作者:行者123 更新时间:2023-11-30 13:04:22 27 4
gpt4 key购买 nike

我尝试使用 IHttpAsyncHandler 在请求管道中注入(inject)解码过滤器,但我发现 Request.Filter 属性被忽略了。

有人成功地将 Request.Filter 与 IHttpAsyncHandler 一起使用了吗?

public class DecodeHttpHandler : IHttpAsyncHandler {
public void ProcessRequest(HttpContext context) {
context.Request.Filter = new DecodeStream(context.Request.Filter);
}
public IAsyncResult BeginProcessRequest(HttpContext context, AsyncCallback cb, object extraData) {
var decodeContext = new DecodeContext(context);
var w = new HttpContextWrapper(context);
w.Request.Filter = new DecodeStream(w.Request.Filter);
return RequestHandler.BeginProcessRequestBase(w, cb, extraData);
}
public void EndProcessRequest(IAsyncResult result){
RequestHandler.EndProcessRequestBase(result);
}
public bool IsReusable {
get {
return true;
}
}
}
public class DecodeStream : Stream {
... details ...
public override int Read(byte[] buffer, int offset, int count) {
// never gets here
int c = _sink.Read(buffer, offset, count);
return c;
}
}

编辑:我找到了另一种不涉及 Request.Filter 的好方法,粘贴在下面。然而,令人费解的是 Request.Filter 根本不起作用。仅供引用,我的用例是在调用第 3 方 RequestHandler 之前进行 URL 解码。

public class UrlDecodeHttpHandler : IHttpAsyncHandler {
public void ProcessRequest(HttpContext context) {
throw new NotImplementedException();
}
public IAsyncResult BeginProcessRequest(HttpContext context, AsyncCallback cb, object extraData) {
var decodeContext = new DecodeContext(context);
return RequestHandler.BeginProcessRequestBase(decodeContext, cb, extraData);
}
public void EndProcessRequest(IAsyncResult result){
RequestHandler.EndProcessRequestBase(result);
}
public bool IsReusable {
get {
return false;
}
}
}
public class DecodeContext : HttpContextWrapper {
private readonly HttpContext _context;
public DecodeContext(HttpContext httpContext) : base(httpContext){
_context = httpContext;
}
public override HttpRequestBase Request {
get { return new DecodeRequest(_context.Request); }
}
}
public class DecodeRequest : HttpRequestWrapper {
public DecodeRequest(HttpRequest request) : base(request) {}
public override Stream InputStream {
get {
string result;
using (var sr = new StreamReader(base.InputStream)) {
result = HttpUtility.UrlDecode(sr.ReadToEnd());
}
return GenerateStreamFromString(result);
}
}
private static Stream GenerateStreamFromString(string s) {
var stream = new MemoryStream();
var writer = new StreamWriter(stream);
writer.Write(s);
writer.Flush();
stream.Position = 0;
return stream;
}
}

最佳答案

在 httphandler 中有很多东西是你不能改变的,因为已经太晚了。您可以尝试在其中放置一个 HTTPModule 进行拦截,看看是否有帮助。请注意,如果我有时间在家,我还没有尝试过这个。

关于c# - IHttpAsyncHandler 和 Request.Filter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9574769/

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