2

我正在寻找可以测试 WCF REST api 调用的 C# 示例测试应用程序?我在网上找不到一个。我还有一些需要传递的 wcf 端点的登录凭据。有人可以指点我示例 test rest api appln 吗?

谢谢

4

2 回答 2

1

I think using WebClient should work for WCF REST services (if you need, you can use credentials, request headers, etc):

private void TestService()
{
    try
    {
        string address = "<WCF REST service address>";
        WebClient client = new WebClient();
        string userName = "<user>";
        string password = "<password>";
        ICredentials creds = new NetworkCredential(userName, password);
        client.Credentials = creds;
        client.Headers[HttpRequestHeader.Authorization] = String.Format("Basic {0}:{1}", userName, password);
        client.Headers[HttpRequestHeader.UserAgent] = @"Mozilla/4.0 (compatible; MSIE 5.5; Windows NT 4.0)";
        Stream data = client.OpenRead(address);
        StreamReader reader = new StreamReader(data);
        string s = reader.ReadToEnd();
        Console.WriteLine(s);
    }
    catch (WebException ex)
    {
        Console.WriteLine(ex.Message);
        if (ex.Response != null)
        {
            Stream strm = ex.Response.GetResponseStream();
            byte[] bytes = new byte[strm.Length];
            strm.Read(bytes, 0, (int)strm.Length);
            string sResponse = System.Text.Encoding.ASCII.GetString(bytes);
            Console.WriteLine(sResponse);
        }
    }
}

EDIT: Example for web application which uses Forms authentication.

My previous example works if the web application allows anonymous users. If not (web.config contains <deny users="?"/> and Anonymous access is enabled in IIS), two requests are required:

  1. the request to the login page to authenticate;

  2. the request to the actual service url.

The auth cookie should be passed to the second request (we use the CookieContainer object to achieve this). The first call passes the user name and password using the POST method. Because my web application uses out-of-the-box login control, I need to pass the view state, event validation, etc. You can get the form data passed during the login from a web browser using Fiddler or Chrome dev tools. This is the code:

private static void TestService()
{
    try
    {
        string loginAddress = "<login url>";
        string serviceAddress = "<service url>";
        HttpWebRequest req = (HttpWebRequest)WebRequest.Create(loginAddress);
        req.Method = "POST";
        string userName = "<user>";
        string password = "<password>";
        CookieContainer cc = new CookieContainer();
        req.CookieContainer = cc;

        StringBuilder sb = new StringBuilder();
        sb.Append(@"__VIEWSTATE=<viewstate>");
        sb.Append(@"&__EVENTVALIDATION=<event validation>");
        sb.Append(@"&ctl00$MainContent$LoginUser$UserName={0}&ctl00$MainContent$LoginUser$Password={1}");
        sb.Append(@"&ctl00$MainContent$LoginUser$LoginButton=Log In");
        string postData = sb.ToString();
        postData = String.Format(postData, userName, password);
        req.ContentType = "application/x-www-form-urlencoded";
        Encoding encoding = new ASCIIEncoding();
        byte[] requestData = encoding.GetBytes(postData);
        req.ContentLength = requestData.Length;

        //write the post data to the request
        using (Stream reqStream = req.GetRequestStream())
        {
            reqStream.Write(requestData, 0, requestData.Length);
            reqStream.Flush();
        }

        HttpWebResponse response = (HttpWebResponse)req.GetResponse(); //first call (login / authentication)

        req = (HttpWebRequest)WebRequest.Create(serviceAddress);
        req.CookieContainer = cc; //set the cookie container which contains the auth cookie
        response = (HttpWebResponse)req.GetResponse(); //second call, the service request
        Stream data = response.GetResponseStream();
        StreamReader reader = new StreamReader(data);
        string s = reader.ReadToEnd();
        Console.WriteLine(s);
    }
    catch (WebException ex)
    {
        Console.WriteLine(ex.Message);
        if (ex.Response != null)
        {
            Stream strm = ex.Response.GetResponseStream();
            byte[] bytes = new byte[strm.Length];
            strm.Read(bytes, 0, (int)strm.Length);
            string sResponse = System.Text.Encoding.ASCII.GetString(bytes);
            Console.WriteLine(sResponse);
        }
    }
}
于 2012-05-22T00:30:03.973 回答
0

我更喜欢用 Fiddler (www.fiddler2.net) 做这种测试

于 2012-05-22T00:38:33.977 回答