2012-08-10 138 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