3

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

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

我怎样才能传递 userId .....

我的服务和我的 Web 应用程序都在同一个解决方案中,但在不同的项目中,并且 userId 的值来自基于登录应用程序的用户的数据库。

4

2 回答 2

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();
            }
于 2012-08-10T08:21:46.307 回答
0

OpenAuth 是一个很好的途径。

查看http://www.codeproject.com/Tips/372422/Secure-WCF-RESTful-service-using-OAUTH

于 2012-08-10T06:22:29.857 回答