HttpModule response change

When calling webservice, I need to change the response text when calling a specific operation.

So I created an HttpModule that caught the answer and changed it.

Below 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 can see, I just cleared the Response object and placed my text.

Is this the right way to do this?

It works, but I think I'm missing something

What do you think?

+4
source share
2 answers

I can’t give you a better answer, but I do it myself when I get JSON from an old ASPX application and it works flawlessly.

So my answer (from personal experience): nothing wrong with that.

+4
source

Your approach may work, but it seems that there is at least some overhead associated with processing the request using the default handler, and then discarding the result of this processing.

A better approach might be the one suggested in this answer to another question , i.e. assigning another 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 request processing logic in the MyHttpHandler class, and you're good to go.

+3
source

Source: https://habr.com/ru/post/1442273/


All Articles