gpt4 book ai didi

asp.net - 从非 Web 客户端调用 ASP.NET 2.0 身份验证服务

转载 作者:行者123 更新时间:2023-12-02 04:14:32 24 4
gpt4 key购买 nike

我正在开发一个调用 ASP.NET 2.0 网站的 .NET 2.0 winforms 应用程序。该网站使用表单例份验证进行身份验证。 web.config中启用了身份验证服务,我做了一些experiments确认我可以通过 JSON 访问该服务。

这是我的问题:是否有任何内置代码可以在纯 .NET 环境(不是 ASP.NET)中使用 System.Web.Extensions Web 服务(authenticationService、profileService 等)?我可以找到使用 Silverlight 和后来的 WCF 服务的示例,但在客户端和服务器上的 2.0 环境中找不到任何示例。将身份验证服务添加为 Web 服务似乎是一种合乎逻辑的方法,但我永远无法让它指向我的开发服务器——我想这可能是一个单独的问题。

如果我必须在较低级别管理 AJAX 请求和响应,这当然是可行的,但如果已经为此目的而设计了某些东西,那肯定会更容易且不易出错。

最佳答案

我从来没有得到答案,但最终在 this tutorial 的帮助下想通了。 .简短的回答是肯定的,我必须在相当低的水平上管理 AJAX 请求/响应。假设您有一个需要进行身份验证的用户名和密码,您首先需要为其获取身份验证 cookie。我用了Json.NET library from Newtonsoft对于 JSON 序列化和反序列化,但你可以使用任何东西。

Cookie GetFormAuthenticationCookie(string username, string password)
{
string uriString = ServerName + AUTH_SERVICE_URL;
Uri uri = new Uri(uriString);

// Need to cast this to HttpWebRequest to set CookieContainer property
// With a null CookieContainer property on the request, we'd get an
// empty HttpWebRequest.Cookies property
HttpWebRequest request = WebRequest.Create(uri) as HttpWebRequest;
request.Method = "POST";
request.ContentType = "application/json; charset=utf-8";
request.CookieContainer = new CookieContainer(); // needed to get non-empty Cookies collection back in response object

// requestContents needs to look like this:
// {
// username = 'theUserName',
// password = 'thePassword',
// createPersistentCookie = false
// }
string requestContents = GetJsonForLoginRequest(username, password);

byte[] postData = Encoding.UTF8.GetBytes(requestContents);
request.ContentLength = postData.Length;
using (Stream dataStream = request.GetRequestStream())
{
dataStream.Write(postData, 0, postData.Length);
}

HttpWebResponse response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode != HttpStatusCode.OK)
{
throw new WebException("Response returned HttpStatusCode " + response.StatusCode);
}

// For now, assuming response ContentType is "application/json; charset=utf-8"
object responseJson;
using (Stream responseStream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(responseStream);
string responseString = reader.ReadToEnd();

responseJson = JavaScriptConvert.DeserializeJson(responseString);
}

if (responseJson is bool)
{
bool authenticated = (bool)responseJson;
if (authenticated)
{
// response was "true"; return the cookie
return response.Cookies[".ASPXFORMSAUTH"];
}
else
{
// apparently the login failed
return null;
}
}
else
{
return null;
}
}

接下来,将 cookie 添加到后续请求中。就我而言,这意味着将 cookie 添加到我正在使用的 Web 服务代理的 CookieContainer 中。

关于asp.net - 从非 Web 客户端调用 ASP.NET 2.0 身份验证服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3468936/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com