6

WebAPI の HttpResponseMessage / HttpRequestMessage 型で実際に送受信される HTTP ヘッダーの生のリストを視覚的に確認することは非常に有益です。つまり、各ヘッダーが新しい行にあり、生成または受信されたものとまったく同じ、単純な古い文字列です。

しかし残念なことに、これらのタイプのいずれも、実際に何が生成されるかを確認できるようには見えません。代わりに、プロパティがあちこちに散らばっています。生の HttpResponseMessage / HttpRequestMessage 型自体の一部、response/request.Content.Headers の一部 (この 2 つは繰り返されません。後者は、プロパティとしてまだカバーされていないもの、通常はカスタム ヘッダー用です)、...そしておそらく Cookieどこかに独自のヘッダーの隠し場所があります。また、これらのヘッダー コレクションのリストを視覚的に確認するのも面倒です。つまり、そのようなコレクションごとに一連のコードを反復処理することになり、さらに混乱します。

しかし、実際の応答/送受信されるリクエストでは、そのような区分はなく、すべての Http ヘッダーを簡単に確認できます。それで、私はどこかでそれを見逃していますか?これらのどこかに、生のヘッダー文字列を単に返すシンプルで直感的なプロパティが実際にありますか? 確かに、応答はすでにヘッダーを受け取り、それらを解析しただけです...その生の文字列はどこかに隠されていますか?

(ところで、私は Fiddler について知っています...そしてそれは完全に満足のいくものではありません。Http ヘッダーの低レベルの混乱に対処しなければならない場合、私が使用しているプログラム型でそれらを表示できることは理にかなっていますしかし、さらに悪いことに、(Win8 上で) Fiddler を使用して localhost を動作させることはまだできません。 )

4

3 に答える 3

-1

Request ヘッダーと Response ヘッダーをキャッチできるようにするために使用するコードは次のとおりです。

*これは Windows フォーム アプリから取得したものです。したがって、txtReceived と txtSent は、Windows フォーム フォーム上の単純な複数行の TextBox です。カーソルはフォームのカーソルです。*

    private HttpClient PrepareHttpClient()
    {
        var client = new HttpClient();

        client.DefaultRequestHeaders.Accept.Add(
            new MediaTypeWithQualityHeaderValue("application/xml"));

        return client;
    }

    private string SendGetRequest(string url)
    {
        //Please be patient ...
        this.Cursor = Cursors.WaitCursor;

        var client = PrepareHttpClient();
        txtSent.Text = url;
        var taskReult = client.GetAsync(new Uri(url));
        HttpResponseMessage httpResponse = taskReult.Result;

        Stream st = httpResponse.Content.ReadAsStreamAsync().Result;
        StreamReader reader = new StreamReader(st);
        string content = reader.ReadToEnd();

        //Reset the cursor shape
        this.Cursor = Cursors.Default;

        txtReceived.Text = FormatResponse(httpResponse, content);

        //For GET we expect a response of 200 OK
        if (httpResponse.StatusCode == HttpStatusCode.OK)
        {
            return content;
        }

        throw new ApplicationException(content);
    }
    /// <summary>
    /// Post to the server using JSON
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="url">The server uri</param>
    /// <param name="e">The object to POST</param>
    /// <returns></returns>
    private string SendPostRequest<T>(string url, T e)
    {
        this.Cursor = Cursors.WaitCursor;
        HttpClient client = new HttpClient();

        // Create the JSON formatter.
        MediaTypeFormatter jsonFormatter = new JsonMediaTypeFormatter();

        // Use the JSON formatter to create the content of the request body.
        HttpContent content = new ObjectContent<T>(e, jsonFormatter);
        Stream st = content.ReadAsStreamAsync().Result;
        StreamReader reader = new StreamReader(st);
        string s = reader.ReadToEnd();


        // Send the request.
        var taskResult = client.PostAsync(url, content);

        //Note: We could simply perform the following line and save some time
        //but then we will not have access to the post content:
        //var taskResult = client.PostAsJsonAsync<T>(url, e);

        HttpResponseMessage httpResponse = taskResult.Result;
        this.Cursor = Cursors.Default;

        txtSent.Text = FormatRequest(httpResponse.RequestMessage, s);

        st = httpResponse.Content.ReadAsStreamAsync().Result;
        reader = new StreamReader(st);
        string responseContent = reader.ReadToEnd();
        txtReceived.Text = FormatResponse(httpResponse, responseContent);

        //For POST we expect a response of 201 Created
        if (httpResponse.StatusCode == HttpStatusCode.Created)
        {
            return responseContent;
        }

        throw new ApplicationException(responseContent);
    }

    /// <summary>
    /// PUT to the server using JSON
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="url"></param>
    /// <param name="e"></param>
    /// <returns></returns>
    private string SendPutRequest<T>(string url, T e)
    {
        this.Cursor = Cursors.WaitCursor;
        HttpClient client = new HttpClient();

        // Create the JSON formatter.
        MediaTypeFormatter jsonFormatter = new JsonMediaTypeFormatter();

        // Use the JSON formatter to create the content of the request body.
        HttpContent content = new ObjectContent<T>(e, jsonFormatter);
        Stream st = content.ReadAsStreamAsync().Result;
        StreamReader reader = new StreamReader(st);
        string s = reader.ReadToEnd();

        // Send the request.
        var taskResult = client.PutAsync(url, content);

        //Note: We could simply perform the following line and save some time
        //but then we will not have access to the post content:
        //var taskResult = client.PutAsJsonAsync<T>(url, e);

        HttpResponseMessage httpResponse = taskResult.Result;

        txtSent.Text = FormatRequest(httpResponse.RequestMessage, s);

        st = httpResponse.Content.ReadAsStreamAsync().Result;
        reader = new StreamReader(st);
        string responseContent = reader.ReadToEnd();
        this.Cursor = Cursors.Default;
        txtReceived.Text = FormatResponse(httpResponse, responseContent);

        //For PUT we expect a response of 200 OK
        if (httpResponse.StatusCode == HttpStatusCode.OK)
        {
            return responseContent;
        }

        throw new ApplicationException(responseContent);
    }

    private string FormatRequest(HttpRequestMessage request, string content)
    {
        return
            string.Format("{0} {1} HTTP/{2}\r\n{3}\r\n{4}",
                request.Method,
                request.RequestUri,
                request.Version,
                request.Headers,
                content);
    }

    private string FormatResponse(HttpResponseMessage result, string content)
    {
        return
            string.Format("HTTP/{0} {1} {2}\r\n{3}\r\n{4}",
                result.Version,
                (int)result.StatusCode,
                result.ReasonPhrase,
                result.Headers,
                content);
    }
于 2013-02-24T12:39:59.567 に答える