2012-08-10 137 views
3

我有一个执行一些操作,做任何事情之前,它向用户授权为目的的REST Web服务调用它一个方法,检查如何授权WCF服务

if(System.Web.HttpContext.Current.Session["UserId"] != null) 
{ 
    string userId = System.Web.HttpContext.Current.Session["UserId"].ToString(); 
} 
else 
{ 
    throw exception; 
} 

我打电话这项服务在我的asp.net web应用程序像下面

HttpWebRequest req = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(uri); 
     req.Method = "POST"; 
     req.ServicePoint.Expect100Continue = false; 
     req.ContentLength = 0; 
     req.ContentType = "application/x-www-form-urlencoded"; 

     if (!string.IsNullOrEmpty(body)) 
     { 
      req.ContentLength = body.Length; 
      ASCIIEncoding encoding = new ASCIIEncoding(); 
      byte[] data = encoding.GetBytes(body); 
      Stream newStream = req.GetRequestStream(); 
      newStream.Write(data, 0, data.Length); 
      newStream.Close(); 
     } 

     HttpWebResponse resp; 
     try 
     { 
      resp = (HttpWebResponse)req.GetResponse(); 
      System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream()); 
      return sr.ReadToEnd().Trim(); 
     } 
     catch (WebException ex) 
     { 
      resp = (HttpWebResponse)ex.Response; 

      //pass on the exception 
      throw ex; 
     } 
    } 

如何传递的用户id .....

我的服务,我的web应用程序都是在同一个解决方案,但在不同的亲ject和userId的值来自基于登录应用程序的用户的数据库。

+0

如何/你在哪里在'Session'设置'UserId'? – 2012-08-10 06:23:25

+0

是的,我在会话中设置userId。一旦我成功登录。 – Popeye 2012-08-10 07:16:27

回答

0

像这样

byte[] postBytes = Encoding.UTF8.GetBytes(userId); 
       req.ContentType = "application/x-www-form-urlencoded"; 
       req.ContentLength = postBytes.Length;   

using(data = req.GetRequestStream()) { 
       data.Write(postBytes, 0, postBytes.Length); 
       data.Close(); 
      } 
+0

这是用来从身体发送数据,如何发送会话 ? – Popeye 2012-08-10 10:21:58