从asp.net网站调用servicestack API的最佳方法是什么?服务正在IIS中运行。 服务堆栈中的所有方法都需要首先进行身份验证。
我尝试使用JsonServiceClient和HttpWebRequest。我第一次进行身份验证时,服务会给我cookie ss-id和ss-pid我存放在cookies集合中。现在当我要求另一种方法它说,你没有被授权。
问题是,在第二个请求中没有维护Cookie。但是,如果您从浏览器中自行测试服务。它首先在授权期间和第二次请求中创建cookie,它会给你正确的响应。
以下是我的代码。使用JsonServiceClient和HttpWebRequest
[HttpPost]
public ActionResult Index(Login loginModel)
{
#region ServiceStack Call
HttpCookie ck;
string baseUrl = "http://192.168.1.101";
var client = new JsonServiceClient(baseUrl);
var authResponse = client.Send<AuthenticateResponse>(new Authenticate
{
UserName = loginModel.UserName,
Password = loginModel.Password,
RememberMe = true
});
foreach (System.Net.Cookie cookie in client.CookieContainer.GetCookies(new Uri(baseUrl)))
{
if (cookie.Name == "ss-id")
{
ck = new HttpCookie(cookie.Name);
ck.Value = cookie.Value;
ck.Expires.AddDays(1); //Check when to expire the cookie
Response.Cookies.Add(ck);
}
}
}
使用HttpWebRequest下面的代码
protected string CallToApi(string baseUrl, bool createCookie)
{
CookieContainer cc = new CookieContainer();
System.Uri uri = new Uri(baseUrl);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.ContentType = @"application/json; charset=utf-8";
request.Timeout = 200000;
request.Accept = "application/json";
request.CookieContainer = new CookieContainer();
try
{
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using (Stream responseStream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(responseStream, System.Text.Encoding.UTF8);
if (reader != null)
{
if (createCookie)
{
//Create Cookies
}
}
return reader.ReadToEnd();
}
}
catch (WebException ex)
{
throw ex;
}
}
如何拨打第二种方法?
http://192.168.1.101/api/teamleaders
网址
调用此Url时,我可以保留我的Cookie吗?或者ServiceStack本身必须开箱即用。
答案 0 :(得分:1)
JsonServiceClient应该保留cookie。我已成功使用以下代码(默认为CredentialsAuthProvider
):
var client = new JsonServiceClient(baseUri);
var authResponse = client.Post(new Auth
{
provider = CredentialsAuthProvider.Name,
UserName = "username",
Password = "password",
RememberMe = true
});
注意:这是版本3.9.71,而不是新的v4堆栈,我还没有机会升级到。同样的应该&#39;使用继承自CredentialsAuthProvider
。