4

Web サービスを呼び出すとき、特定の操作を呼び出すときに応答テキストを変更する必要があります。

そのため、応答をキャッチして変更する HttpModule を作成しました。

コードの下:

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()
  {
  }
}

ご覧のとおり、Response オブジェクトをクリアしてテキストを入力するだけです。

それを行う適切な方法はありますか?

動作していますが、何かが足りないと思います

どう思いますか ?

4

2 に答える 2

3

あなたのアプローチはうまくいくかもしれませんが、デフォルトハンドラーを使用してリクエストを処理し、その処理の結果を捨てることに関連するオーバーヘッドが少なくともあるようです。

より良いアプローチは、別の質問に対するこの回答で提案されているもの、つまり、現在処理されているリクエストに別のハンドラーを割り当てることです。

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クラスに入れるだけで、準備完了です。

于 2014-05-29T13:15:02.863 に答える
3

ベスト プラクティスの回答を提供することはできませんが、古い学校の ASPX アプリケーションから JSON を出力しているときにこれを自分で行い、問題なく動作します。

だから私の答えは(個人的な経験から)です:これは何も悪いことではありません.

于 2012-10-26T08:52:59.590 に答える