C# HttpModule更改响应
当调用webservice时,我需要在调用特定操作时更改响应文本 因此,我创建了HttpModule来捕获响应并对其进行更改 代码如下:C# HttpModule更改响应,c#,asp.net,http,response,C#,Asp.net,Http,Response,当调用webservice时,我需要在调用特定操作时更改响应文本 因此,我创建了HttpModule来捕获响应并对其进行更改 代码如下: public class BeginEnd : IHttpModule { public void Init(HttpApplication context) { context.EndRequest += (o, e) => { HttpContext currContext = HttpContex
public class BeginEnd : IHttpModule
{
public void Init(HttpApplication context)
{
context.EndRequest += (o, e) =>
{
HttpContext currContext = HttpContext.Current;
NameValueCollection collection = currContext.Request.QueryString;
if ( collection.Count > 0
&& collection["op"] != null
&& collection["op"] == "ChangeService" )
{
string xmlOther = "<root>My Test</root>";
currContext.Response.Clear();
currContext.Response.Write(xmlOther);
currContext.Response.End();
}
};
}
public void Dispose()
{
}
}
公共类begined:IHttpModule
{
公共void Init(HttpApplication上下文)
{
context.EndRequest+=(o,e)=>
{
HttpContext currContext=HttpContext.Current;
NameValueCollection=currContext.Request.QueryString;
如果(集合计数>0
&&集合[“op”]!=null
&&集合[“op”]=“ChangeService”)
{
string xmlOther=“我的测试”;
currContext.Response.Clear();
currContext.Response.Write(xmlOther);
currContext.Response.End();
}
};
}
公共空间处置()
{
}
}
正如你们所看到的,我只是清除了Response对象,然后把我的文本放进去
这是一个正确的方法吗
它起作用了,但我想我遗漏了什么
你觉得怎么样?我不能给你一个最佳实践的答案,但我自己这样做是为了从一个旧的skool ASPX应用程序输出JSON,它工作得完美无缺
因此,我的回答是(根据个人经验):这没什么错。您的方法可能有效,但看起来至少有一些开销与使用默认处理程序处理请求,然后丢弃处理结果相关 更好的方法可能是中建议的方法,即为当前处理的请求分配不同的处理程序:
public class MyHttpModule : IHttpModule
{
public void Init(HttpApplication application)
{
application.PostAuthenticateRequest += app_PostAuthenticateRequest;
}
void app_PostAuthenticateRequest(object sender, EventArgs e)
{
var context = HttpContext.Current;
var queryString = context.Response.QueryString;
// queryString["op"] will never fail, just compare its value
if (queryString["op"] == "ChangeService")
{
context.RemapHandler(new MyHttpHandler());
}
}
public void Dispose() { }
}
然后,只需将处理请求的逻辑放入MyHttpHandler
类,就可以开始了