如何将WCF rest api集成到应用程序中

时间:2012-05-21 22:46:19

标签: c# wcf rest

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

由于

2 个答案:

答案 0 :(得分:1)

我认为使用WebClient应该适用于WCF REST服务(如果需要,可以使用凭据,请求标头等):

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

编辑:使用表单身份验证的Web应用程序示例。

如果Web应用程序允许匿名用户,我之前的示例有效。如果不是(web.config包含<deny users="?"/>并且在IIS中启用了匿名访问),则需要两个请求:

  1. 对登录页面进行身份验证的请求;

  2. 对实际服务网址的请求。

  3. 应该将auth cookie传递给第二个请求(我们使用CookieContainer对象来实现此目的)。 第一个调用使用POST方法传递用户名和密码。因为我的Web应用程序使用开箱即用的登录控件,所以我需要传递视图状态,事件验证等。您可以使用Fiddler或Chrome开发工具从Web浏览器获取登录期间传递的表单数据。这是代码:

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

答案 1 :(得分:0)

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