HttpWebRequest not sending UserAgent

2019-02-24 23:11发布

问题:

I'm new to looking at the whole Web side of .net, and I've run into a slight issue.

I'm trying to do a HttpWebRequest as below:

String uri = "https://skyid.sky.com/signup/";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.UserAgent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)";
request.Method = "GET";
request.GetResponse();

Where the uri is pointing to a HTTPS site. But once I look at this in Fiddler, it has removed my UserAgent and only shows Host and Connection: Keep-Alive.

CONNECT skyid.sky.com:443 HTTP/1.1
Host: skyid.sky.com
Connection: Keep-Alive

Is this normal with HTTPS or am I simply missing something? Maybe I'm even missing something in Fiddler that it's not showing this to me.

Any help will be appreciated, thanks all!

回答1:

I don't think that you are looking at the correct Fiddler line. What you have shown is a CONNECT verb, not GET. The UserAgent should be properly set using the request.UserAgent property. Another way to debug the request is to configure network tracing at your application level which I personally prefer compared to Fiddler:

<configuration>
    <system.diagnostics>
        <sources>
            <source name="System.Net" tracemode="protocolonly" maxdatasize="1024">
                <listeners>
                    <add name="System.Net"/>
                </listeners>
            </source>
        </sources>
        <switches>
            <add name="System.Net" value="Verbose"/>
        </switches>
        <sharedListeners>
            <add 
                name="System.Net"
                type="System.Diagnostics.TextWriterTraceListener"
                initializeData="network.log"
            />
        </sharedListeners>
        <trace autoflush="true"/>
    </system.diagnostics>
</configuration>