Reputation: 3374
When invoking webservice I need to change response text when invoking certain operation .
Therefore I created HttpModule that catch response and change it.
Below the code :
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()
{
}
}
So as you see, I just clear Response object and put my text.
Is is a proper way to do it ?
It's working , but I think that I missing something
What do you think ?
Upvotes: 4
Views: 6351
Reputation: 9498
Your approach might work, but it looks like there at least some overhead associated with processing the request using its default handler and then throwing the result of that processing away.
A better approach might be the one proposed in this answer to a different question, i.e. assigning a different handler to the currently processed request:
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() { }
}
Then, just put the logic of treating the request into the MyHttpHandler
class and you're good to go.
Upvotes: 3
Reputation: 12173
I can't give you a best-practice answer, but I do this myself for when I am outputting JSON from an old-skool ASPX application, and it works flawlessly.
So my answer is (out of personal experience): nothing wrong with this.
Upvotes: 3