asp.net 截取Http asp.net 截取Http请求的实现代码

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

asp.net 截取Http asp.net 截取Http请求的实现代码

  2021-03-18 我要评论
想了解asp.net 截取Http请求的实现代码的相关内容吗,在本文为您仔细讲解asp.net 截取Http的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:asp.net,截取Http,下面大家一起来学习吧。
1:前言
本篇文章比较短,主要是因为我的一个随想产生的一段代码。 这段代码的功能你可以叫做是简单的Http服务器也可以叫做Http请求截取。它实现的功能就是截取Http请求然后自己做处理。
2:代码
复制代码 代码如下:

public class HttpServer : IDisposable
{
private HttpListener listener;
public void Start()
{
listener = new HttpListener();
listener.Prefixes.Add("http://localhost/");
listener.AuthenticationSchemes = AuthenticationSchemes.IntegratedWindowsAuthentication | AuthenticationSchemes.Anonymous;
listener.Start();
listener.BeginGetContext(GetContext, null);
}
private void GetContext(IAsyncResult ar)
{
HttpListenerRequest Request;
HttpListenerResponse Response;
try
{
HttpListenerContext ctx = listener.EndGetContext(ar);
Request = ctx.Request;
Response = ctx.Response;
//setup waiting for the next request
listener.BeginGetContext(GetContext, null);
}
catch (InvalidOperationException)
{
return;
}
catch (HttpListenerException)
{
return;
}
try
{
var sw = new StreamWriter(Response.OutputStream);
sw.Write(@"<html><body><p>你的请求已经被截取</p></body></html>");
sw.Flush();
}
finally
{
Response.OutputStream.Flush();
Response.Close();
}
}
public void Dispose()
{
if (listener != null)
listener.Stop();
}
}

3:简单解释一下
代码的核心就是HttpListener,通过它去侦听一个端口,当有请求的时候BeginGetContext交给GetContext方法进行异步处理,在这个方法的内部首先实现的就是重新监听。然后进行自己的处理。
呵呵,这段代码有什么其他用处待考虑。

猜您喜欢

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们