我有一个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的值来自基于用户登录应用程序的数据库。
答案 0 :(得分:0)
OpenAuth是一条很好的途径。
查看http://www.codeproject.com/Tips/372422/Secure-WCF-RESTful-service-using-OAUTH
答案 1 :(得分: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();
}