查看原始标题将被发送/在Htt的presponseMessage / Htt的prequestMessage收到(System.Net.Http,的WebAPI) [英] View Raw Headers that will be sent/received in HttpResponseMessage / HttpRequestMessage (System.Net.Http, WebAPI)

查看:227
本文介绍了查看原始标题将被发送/在Htt的presponseMessage / Htt的prequestMessage收到(System.Net.Http,的WebAPI)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

直观地看到HTTP标头的原始列表将实际发送或的WebAPI的Htt的presponseMessage / Htt的prequestMessage类型收到它可以是非常有益的。我的意思只是一个普通的老字符串,在一个新行每个头,究竟是什么产生或接收。

It can be extremely beneficial to visually see the raw list of Http Headers that will actually be sent or received in WebAPI's HttpResponseMessage / HttpRequestMessage types. I mean just a plain old string, with each header on a new line, exactly what is generated or received.

但不幸的是,它看起来并不像这两种类型的让你只看到实际获取生成的内容。相反,也有到处散布特性。在一些原始的Htt presponseMessage / Htt的prequestMessage类型本身,有的在响应/ request.Content.Headers(两者不重复,后者则是那些尚未覆盖的特性,通常用于自定义标题),...也许某处饼干都有自己的头藏匿。和视觉越来越看到标题集合这些名单是一种痛苦,以及,即你最终为每个这样的收集一堆迭代code ...更多的混乱。

But unfortunately, it does not look like either of these types allows you to just see what actually gets generated. Instead, there are properties scattered everywhere. Some in the raw HttpResponseMessage / HttpRequestMessage types themselves, some in the response/request.Content.Headers (the two do not repeat, the latter is for ones not already covered as properties, typically for custom headers), ... and maybe Cookies somewhere gets a stash of its own headers. And visually getting to see those lists of Header collections is a pain as well, i.e. you end up with a bunch of iterating code for each such collection ... more mess.

但是,在实际发送的响应/请求/接收,不存在这样的划分,并且这是简单地看到所有HTTP头。 所以我错过它的地方?有没有实际上是一个简单而直观的某处财产,这些仅仅返回原标题字符串?当然,响应已经收到了头,只是解析他们......是原始字符串隐藏的地方?

But in the actual response / request sent / received, there is no such division, and it is simple to see all Http headers. So am I missing it somewhere? Is there actually a simple and intuitive property somewhere in these that simply returns the raw headers string? Certainly the response already received the headers and just parsed them ... is that raw string hidden somewhere?

(顺便说一句,我是知道的小提琴手......这是完全不能令人满意的。如果我有处理HTTP头的低级别搞乱,那么它是一个很好的意识,能够与编程I型来查看我使用生成和接收他们。但糟糕的时候,我仍然无法获得本地主机与提琴手(上Win8的),它的无效使用了许多调试方案,所有我想要做的就是看到臭头即会工作产生。)

(BTW, I know about Fiddler... and that is entirely unsatisfactory. If I am having to deal with low-level messing of Http headers, then it makes good sense to be able to view them with the programmatic type I am using to generate and receive them with. But worse off, I still can't get localhost to work with Fiddler (on Win8), which invalidates its use for many debugging scenarios where all I want to do is see the stinking headers that will be generated.)

推荐答案

下面是code我使用以便能够赶上请求和响应头:

Here is the code I use in order to be able to catch the Request and Response headers:

*这是从Windows窗体采取的应用程序,以便:txtReceived和txtSent是WindowsForms形式简单的多行文本框。且光标窗体的光标。 *

*This is taken from a Windows Forms app so: txtReceived and txtSent are simple multiline TextBoxes on a WindowsForms form. and the cursor is the Form's cursor. *

    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);
    }

这篇关于查看原始标题将被发送/在Htt的presponseMessage / Htt的prequestMessage收到(System.Net.Http,的WebAPI)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆