I adapted this code from a post by Andy Wiggly (who is not just "some guy" - he co-wrote "MS .NET Compact Framework" for MS Press):

WebRequest request = HttpWebRequest.Create(uri);
request.Method = Enum.ToObject(typeof(HttpMethods), method).ToString();
request.ContentType = contentType;
((HttpWebRequest)request).Accept = contentType;
((HttpWebRequest)request).KeepAlive = false;
((HttpWebRequest)request).ProtocolVersion = HttpVersion.Version10;

if (method != HttpMethods.GET && method != HttpMethods.DELETE)
{
    Encoding encoding = Encoding.UTF8;
    request.ContentLength = encoding.GetByteCount(data);
    //request.ContentType = contentType; <= redundant; set above
    request.GetRequestStream().Write(
      encoding.GetBytes(data), 0, (int)request.ContentLength);
    request.GetRequestStream().Close();
}

Note how in the first block of code I had to cast "request" as HttpWebRequest; within the conditional, though, casting is unnecessary. Why the difference? Should "WebRequest" be "HttpWebRequest" instead? If I do that, the casting is greyed out, indicating it's unnecessary, but Wiggly must have done that for a reason, and still: why is the casting obviated within the conditional block?

有帮助吗?

解决方案

HttpWebRequest.Create() is kind of a static factory. You cannot override the behaviour in a derived class. Depending on the URI you provide, it can create a HttpWebRequest or a FtpWebRequest. Which are derived from WebRequest. When you know you're creating a Http request, then i suggest you do the following:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri)

or

var request = (HttpWebRequest)WebRequest.Create(uri)

When you want to access the special properties/methods of the derived class which aren't available in the base class, you have to do this cast.

e.g. KeepAlive is not available in the WebRequest base class because it belongs to HttpWebRequest.

Other properties like Method is defined in the base class and therefore you don't need the cast.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top