简体   繁体   English

最佳实践,创建WebRequest的界面

[英]Best practice, create interface of WebRequest

如果要创建System.net.WebRequest的接口,最好的方法是什么?

To David's point, you first need to determine what it is that you want to do with the interface before you can decide what members it needs. 就David而言,您首先需要确定要对接口执行的操作,然后才能确定所需的成员。 If you want an interface for unit testing, I would recommend a separate approach. 如果您想要一个用于单元测试的界面,我建议您使用另一种方法。 Take a look at the answer with the most votes to this question . 看一下对这个问题票数最多的答案。

However, to answer your question strictly as asked, since you can't modify the WebRequest class, you'd first want to subclass it as so: 但是,要严格按照要求回答您的问题,由于您无法修改WebRequest类,因此您首先需要将其子类化为:

public class MyWebRequest : WebRequest, IMyWebRequest
{
}

You could then add all of the public members exposed by WebRequest to IMyWebRequest as so (remove members that you don't want exposed): 然后,您可以将WebRequest公开的所有公共成员添加到IMyWebRequest中(删除您不想公开的成员):

public interface IMyWebRequest
{
    Stream GetRequestStream();
    WebResponse GetResponse();
    IAsyncResult BeginGetResponse(AsyncCallback callback, object state);
    WebResponse EndGetResponse(IAsyncResult asyncResult);
    IAsyncResult BeginGetRequestStream(AsyncCallback callback, object state);
    Stream EndGetRequestStream(IAsyncResult asyncResult);
    void Abort();
    RequestCachePolicy CachePolicy { get; set; }
    string Method { get; set; }
    Uri RequestUri { get; }
    string ConnectionGroupName { get; set; }
    WebHeaderCollection Headers { get; set; }
    long ContentLength { get; set; }
    string ContentType { get; set; }
    ICredentials Credentials { get; set; }
    bool UseDefaultCredentials { get; set; }
    IWebProxy Proxy { get; set; }
    bool PreAuthenticate { get; set; }
    int Timeout { get; set; }
    AuthenticationLevel AuthenticationLevel { get; set; }
    TokenImpersonationLevel ImpersonationLevel { get; set; }
    object GetLifetimeService();
    object InitializeLifetimeService();
    ObjRef CreateObjRef(Type requestedType);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM