本文整理汇总了C#中System.Net.Cookie类的典型用法代码示例。如果您正苦于以下问题:C# Cookie类的具体用法?C# Cookie怎么用?C# Cookie使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
Cookie类属于System.Net命名空间,在下文中一共展示了Cookie类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。
示例1: SendLoginData
private async Task<bool> SendLoginData(string username, string password)
{
CookieContainer cookies = await _webManager.PostData(
Constants.LOGIN_URL, string.Format(
"action=login&username={0}&password={1}",
username.Replace(" ", "+"),
WebUtility.UrlEncode(password)));
if (cookies.Count < 2)
{
return false;
}
var fixedCookieContainer = new CookieContainer();
// TODO: HUGE HACK. For some reason Windows Phone does not use the Domain Key on a cookie, but only the domain when making requests.
// Windows 8 won't break on it, but Windows Phone will, since the Domain Key and Domain are different on SA.
// We need to move this code to a more common place.
foreach (Cookie cookie in cookies.GetCookies(new Uri(Constants.COOKIE_DOMAIN_URL)))
{
var fixedCookie = new Cookie(cookie.Name, cookie.Value, "/", ".somethingawful.com");
fixedCookieContainer.Add(new Uri(Constants.COOKIE_DOMAIN_URL), fixedCookie);
}
await _localStorageManager.SaveCookie(Constants.COOKIE_FILE, cookies, new Uri(Constants.COOKIE_DOMAIN_URL));
return true;
}
开发者ID:Gluco,项目名称:AwfulMetro,代码行数:28,代码来源:AuthenticationManager.cs
示例2: ConvertToCookieContainer
/// <summary>
/// convert cookies string to CookieContainer
/// </summary>
/// <param name="cookies"></param>
/// <returns></returns>
public static CookieContainer ConvertToCookieContainer(Dictionary<string, string> cookies)
{
CookieContainer cookieContainer = new CookieContainer();
foreach (var cookie in cookies)
{
string[] strEachCookParts = cookie.Value.Split(';');
int intEachCookPartsCount = strEachCookParts.Length;
foreach (string strCNameAndCValue in strEachCookParts)
{
if (!string.IsNullOrEmpty(strCNameAndCValue))
{
Cookie cookTemp = new Cookie();
int firstEqual = strCNameAndCValue.IndexOf("=");
string firstName = strCNameAndCValue.Substring(0, firstEqual);
string allValue = strCNameAndCValue.Substring(firstEqual + 1, strCNameAndCValue.Length - (firstEqual + 1));
cookTemp.Name = firstName;
cookTemp.Value = allValue;
cookTemp.Path = "/";
cookTemp.Domain = cookie.Key;
cookieContainer.Add(cookTemp);
}
}
}
return cookieContainer;
}
开发者ID:yonglehou,项目名称:ToolRepository,代码行数:32,代码来源:Http3Helper.cs
示例3: Meteor
public Meteor()
{
cookies = new Cookie();
cookies.Domain = "http://www.meteor.ie";
cookies.Name = "meteor";
cookieContainer = new CookieContainer();
}
开发者ID:miconico,项目名称:AIB24Base,代码行数:7,代码来源:clsMeteor.cs
示例4: GetFormsCredentials
public bool GetFormsCredentials(out Cookie authCookie, out string user, out string password, out string authority)
{
// Do not use forms credentials to authenticate.
authCookie = null;
user = password = authority = null;
return false;
}
开发者ID:HarryMcCarney,项目名称:LarrysListApi,代码行数:7,代码来源:ReportServerCredentials.cs
示例5: GetHeaderValue
public string GetHeaderValue(Cookie cookie)
{
var path = cookie.Expires == Session
? "/"
: cookie.Path ?? "/";
var sb = new StringBuilder();
sb.AppendFormat("{0}={1};path={2}", cookie.Name, cookie.Value, path);
if (cookie.Expires != Session)
{
sb.AppendFormat(";expires={0}", cookie.Expires.ToString("R"));
}
if (!string.IsNullOrEmpty(cookie.Domain))
{
sb.AppendFormat(";domain={0}", cookie.Domain);
}
else if (EndpointHost.Config.RestrictAllCookiesToDomain != null)
{
sb.AppendFormat(";domain={0}", EndpointHost.Config.RestrictAllCookiesToDomain);
}
if (cookie.Secure)
{
sb.Append(";Secure");
}
if (cookie.HttpOnly)
{
sb.Append(";HttpOnly");
}
return sb.ToString();
}
开发者ID:ELHANAFI,项目名称:ServiceStack,代码行数:35,代码来源:Cookies.cs
示例6: Get
public static bool Get(string route, IEnumerable<KeyValuePair<string, string>> parameters, out JObject result, Cookie cookie = null)
{
KeyValuePair<bool, string> get = GetAsync(route, parameters, cookie).Result;
result = get.Key ? JObject.Parse(get.Value) : null;
return get.Key;
}
开发者ID:Darth-Alex,项目名称:client,代码行数:7,代码来源:Http.cs
示例7: GetFormsCredentials
public bool GetFormsCredentials(out Cookie authCookie, out string user,
out string password, out string authority)
{
authCookie = null;
user = password = authority = null;
return false;
}
开发者ID:hatefi-arman,项目名称:Modules,代码行数:7,代码来源:ReportViewer.aspx.cs
示例8: TestDeep
public void TestDeep(string username, string password)
{
Blog service = new Blog();
string ticket = service.Login(username, password);
Cookie cookie = new Cookie(sDBlogAuthCookieName, ticket, "/", "localhost");
TestDeep(cookie);
}
开发者ID:dblock,项目名称:dblog,代码行数:7,代码来源:Web.PagesTest.cs
示例9: AuthenticateUser
private static bool AuthenticateUser(string user, string password, out Cookie authCookie)
{
var request = WebRequest.Create("https://localhost/account/LogIn") as HttpWebRequest;
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.CookieContainer = new CookieContainer();
var authCredentials = "UserName=" + user + "&Password=" + password;
byte[] bytes = System.Text.Encoding.UTF8.GetBytes(authCredentials);
request.ContentLength = bytes.Length;
using (var requestStream = request.GetRequestStream())
{
requestStream.Write(bytes, 0, bytes.Length);
}
using (var response = request.GetResponse() as HttpWebResponse)
{
authCookie = response.Cookies[FormsAuthentication.FormsCookieName];
}
if (authCookie != null)
{
return true;
}
else
{
return false;
}
}
开发者ID:provenstyle,项目名称:SignalRChat,代码行数:29,代码来源:Program.cs
示例10: Context
public void Context()
{
File.WriteAllText(AuthenticationCookiePersister.PersistentCookiePath, "nonsence nonsence nonsence nonsence nonsence nonsence nonsence");
var authenticationCookiePersister = new AuthenticationCookiePersister();
_cookie = authenticationCookiePersister.GetPersistentAuthenticationCookie();
}
开发者ID:xhafan,项目名称:eshop-coreddd,代码行数:7,代码来源:when_getting_persistent_cookie_which_cannot_be_deserialized.cs
示例11: OnIdentityProviderTapped
private async void OnIdentityProviderTapped(object sender, TappedRoutedEventArgs e)
{
var identityProvider = (IdentityProvider)((FrameworkElement)e.OriginalSource).DataContext;
var webAuthenticationResult = await WebAuthenticationBroker.AuthenticateAsync(
WebAuthenticationOptions.None,
new Uri(identityProvider.LoginUrl),
new Uri("http://authentication.brainthud.com/api/federationcallback/end"));
var start = webAuthenticationResult.ResponseData.LastIndexOf('=') + 1;
var nameIdentifier = webAuthenticationResult.ResponseData.Substring(start, webAuthenticationResult.ResponseData.Length - start);
var cookies = this.getCookies(nameIdentifier);
var uri = new Uri(@"http://www.brainthud.com/api/Cards/");
var cookieContainer = new CookieContainer();
foreach(var cookie in cookies)
{
var cookieItem = new Cookie(cookie.Key, cookie.Value);
cookieContainer.Add(uri, cookieItem);
}
var handler = new HttpClientHandler();
handler.CookieContainer =cookieContainer;
var client = new HttpClient(handler);
var response = client.GetAsync(uri).Result;
var result = response.Content.ReadAsStringAsync().Result;
var x = result;
}
开发者ID:aenmeyk,项目名称:BrainThud,代码行数:29,代码来源:LoginView.xaml.cs
示例12: AddCookie
public static void AddCookie(this List<Cookie> cookieList, string setCookieFormat)
{
var bits = setCookieFormat.Split(';');
string key, value;
GetKeyValue(bits[0], '=', out key, out value);
var c = new Cookie(key, value);
for(var i = 1; i < bits.Length; i++) {
GetKeyValue(bits[1], '=', out key, out value);
switch(key) {
case "expires":
c.Expires = DateTime.Parse(value);
break;
case "path":
c.Path = value;
break;
case "domain":
c.Domain = value;
break;
case "secure":
c.Secure = value == "true";
break;
}
}
cookieList.AddCookie(c);
}
开发者ID:piscisaureus,项目名称:coapp,代码行数:25,代码来源:CookieExtensions.cs
示例13: GetFedAuthCookie
/// <summary>
/// Performs active authentication against ADFS using the trust/13/usernamemixed ADFS endpoint.
/// </summary>
/// <param name="siteUrl">Url of the SharePoint site that's secured via ADFS</param>
/// <param name="serialNumber">Serial Number of the Current User > My Certificate to use to authenticate </param>
/// <param name="certificateMixed">Uri to the ADFS certificatemixed endpoint</param>
/// <param name="relyingPartyIdentifier">Identifier of the ADFS relying party that we're hitting</param>
/// <param name="logonTokenCacheExpirationWindow"></param>
/// <returns>A cookiecontainer holding the FedAuth cookie</returns>
public CookieContainer GetFedAuthCookie(string siteUrl, string serialNumber, Uri certificateMixed, string relyingPartyIdentifier, int logonTokenCacheExpirationWindow)
{
CertificateMixed adfsTokenProvider = new CertificateMixed();
var token = adfsTokenProvider.RequestToken(serialNumber, certificateMixed, relyingPartyIdentifier);
string fedAuthValue = TransformSamlTokenToFedAuth(token.TokenXml.OuterXml, siteUrl, relyingPartyIdentifier);
// Construct the cookie expiration date
TimeSpan lifeTime = SamlTokenlifeTime(token.TokenXml.OuterXml);
if (lifeTime == TimeSpan.Zero)
{
lifeTime = new TimeSpan(0, 60, 0);
}
int cookieLifeTime = Math.Min((lifeTime.Hours * 60 + lifeTime.Minutes), logonTokenCacheExpirationWindow);
DateTime expiresOn = DateTime.Now.AddMinutes(cookieLifeTime);
CookieContainer cc = null;
if (!string.IsNullOrEmpty(fedAuthValue))
{
cc = new CookieContainer();
Cookie samlAuth = new Cookie("FedAuth", fedAuthValue);
samlAuth.Expires = expiresOn;
samlAuth.Path = "/";
samlAuth.Secure = true;
samlAuth.HttpOnly = true;
Uri samlUri = new Uri(siteUrl);
samlAuth.Domain = samlUri.Host;
cc.Add(samlAuth);
}
return cc;
}
开发者ID:stijnbrouwers,项目名称:PnP-Sites-Core,代码行数:43,代码来源:CertificateMixed.cs
示例14: Get
/// <summary>
/// Get request to a website
/// </summary>
/// <param name="uri">Uri to request</param>
/// <param name="host">Host for header</param>
/// <param name="cookie">Cookie for authentication</param>
/// <param name="referer">Referer for header</param>
/// <param name="action">Callback</param>
/// <param name="userAgent">Useragent for header</param>
/// <remarks>Requires refactoring, make it more general and replace CrawlString with it</remarks>
public static void Get(String uri, String host, Cookie cookie, String referer, Action<PostResult> action, String userAgent)
{
using (var client = new WebClientEx())
{
if (cookie != null)
{
client.CookieContainer.Add(cookie);
}
client.Headers["Accept"] = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
client.Headers["Accept-Language"] = "de-de,de;q=0.8,en-us;q=0.5,en;q=0.3";
client.Headers["Cache-Control"] = "no-cache";
client.Headers["User-Agent"] = userAgent;
if (!String.IsNullOrEmpty(referer))
{
client.Headers["Referer"] = referer;
}
if (!String.IsNullOrEmpty(host))
{
client.Headers["Host"] = host;
}
client.Headers["X-Requested-With"] = "XMLHttpRequest";
var response = client.DownloadString(uri);
PostResult ps = new PostResult() { Result = response };
action(ps);
}
}
开发者ID:mercutiodesign,项目名称:TradingPostNotifier,代码行数:36,代码来源:ScrapeHelper.cs
示例15: SendHttpPostRequest
/// <summary>
/// ͬ������HttpRequest
/// </summary>
/// <param name="cookie"></param>
/// <param name="url"></param>
/// <param name="postData"></param>
/// <returns></returns>
public static HttpWebResponse SendHttpPostRequest(Cookie cookie, string url, string postData)
{
//���https�µ�֤������
HttpRequestCredentialHelper.SetDefaultCredentialValidationLogic();
var request = HttpWebRequest.Create(url) as HttpWebRequest;
//������������ΪPOST
request.Method = "POST";
//����Post������
if (!string.IsNullOrEmpty(postData))
{
request.ContentLength = postData.Length;
request.ContentType = "application/x-www-form-urlencoded";
using (var writer = new StreamWriter(request.GetRequestStream()))
{
writer.Write(postData);
writer.Close();
}
}
//��Cookie�����������÷�����֪����ǰ�û������
var container = new CookieContainer();
request.CookieContainer = container;
if (cookie != null)
{
container.SetCookies(new Uri(Constants.ROOT_URL), string.Format("{0}={1}", cookie.Name, cookie.Value));
var logger = DependencyResolver.Resolve<ILoggerFactory>().Create(typeof(HttpWebRequestHelper));
logger.InfoFormat("HttpWebRequest CookieName:{0}, Value:{1}", cookie.Name, cookie.Value);
}
return request.GetResponse() as HttpWebResponse;
}
开发者ID:codesharp,项目名称:cooper,代码行数:41,代码来源:HttpWebRequestHelper.cs
示例16: ToNetCookie
static Cookie ToNetCookie(NSHttpCookie cookie)
{
var nc = new Cookie(cookie.Name, cookie.Value, cookie.Path, cookie.Domain);
nc.Secure = cookie.IsSecure;
return nc;
}
开发者ID:diegofrata,项目名称:ModernHttpClient,代码行数:7,代码来源:NativeCookieHandler.cs
示例17: ToCookie
public static Cookie ToCookie(this string str)
{
if (string.IsNullOrWhiteSpace(str))
return null;
var elements = str.SplitClean(';').ToArray();
var keyValues = new NameValueCollection();
var cookie = new Cookie();
var nameValue = elements[0].SplitClean('=').ToArray();
cookie.Name = nameValue[0];
cookie.Value = nameValue[1];
foreach (var element in elements.Skip(1))
{
if (element.Contains('='))
{
var keyValue = element.Split('=');
keyValues.Add(keyValue[0].ToLower(), keyValue[1]);
}
// else if (element.ToLower() == "secure")
// {
// cookie.Secure = true;
// }
// else if (element.ToLower() == "httponly")
// {
// cookie.HttpOnly = true;
// }
}
cookie.Domain = keyValues["domain"];
cookie.Path = keyValues["path"];
return cookie;
}
开发者ID:ztmdsbt-studio,项目名称:Purchase,代码行数:31,代码来源:Extendtions.cs
示例18: Login
public bool Login(string userName, string password, out Cookie authCookie)
{
var request=WebRequest.Create(ConfigurationManager.AppSettings["RemoteServer"] + "api/authorize") as HttpWebRequest;
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.CookieContainer = new CookieContainer();
var authCredentials = "userName=" + userName + "&password=" + password;
byte[] bytes = System.Text.Encoding.UTF8.GetBytes(authCredentials);
request.ContentLength = bytes.Length;
using (var requestStream = request.GetRequestStream())
{
requestStream.Write(bytes, 0, bytes.Length);
}
using (var response = request.GetResponse() as HttpWebResponse)
{
authCookie = response.Cookies[".AspNet.ApplicationCookie"];
}
if (authCookie != null)
{
return true;
}
else
{
return false;
}
}
开发者ID:ishwormali,项目名称:practices,代码行数:29,代码来源:LoginManager.cs
示例19: ValidateUserIdWithRequestCookie
/// <summary>
/// Tests the scenario when the initial request contains a cookie (corresponding to user), in which case, the response should contain a similar cookie with the information
/// replicated into the listener data.
/// </summary>
protected void ValidateUserIdWithRequestCookie(string requestPath, int testListenerTimeoutInMs, int testRequestTimeOutInMs, Cookie[] additionalCookies = null)
{
DateTimeOffset time = DateTimeOffset.UtcNow;
List<Cookie> cookies = new List<Cookie>();
int additionalCookiesLength = 0;
if (null != additionalCookies)
{
cookies.AddRange(additionalCookies);
additionalCookiesLength = additionalCookies.Length;
}
string userCookieStr = "userId|" + time.ToString("O");
var cookie = new Cookie(CookieNames.UserCookie, userCookieStr);
cookies.Add(cookie);
var requestResponseContainer = new RequestResponseContainer(cookies.ToArray(), requestPath, this.Config.ApplicationUri, testListenerTimeoutInMs, testRequestTimeOutInMs);
requestResponseContainer.SendRequest();
var userCookie = requestResponseContainer.CookieCollection.ReceiveUserCookie();
var item = Listener.ReceiveItemsOfType<TelemetryItem<RequestData>>(
1,
testListenerTimeoutInMs)[0];
Assert.AreEqual("OK", requestResponseContainer.ResponseTask.Result.ReasonPhrase);
Assert.AreEqual(2 + additionalCookiesLength, requestResponseContainer.CookieCollection.Count);
Assert.AreEqual("userId", item.UserContext.Id);
Assert.AreEqual(time, item.UserContext.AcquisitionDate.Value);
Assert.AreEqual(userCookieStr, userCookie);
Assert.AreEqual(userCookie, item.UserContext.Id + "|" + item.UserContext.AcquisitionDate.Value.ToString("O"));
}
开发者ID:gregjhogan,项目名称:ApplicationInsights-server-dotnet,代码行数:33,代码来源:UserSessionTestBase.cs
示例20: DeleteCookie
/// <summary>
/// Deletes a specified cookie by setting its value to empty and expiration to -1 days
/// </summary>
public void DeleteCookie(string cookieName)
{
var cookie = new Cookie(cookieName, string.Empty, "/") {
Expires = DateTime.UtcNow.AddDays(-1)
};
AddCookie(cookie);
}
开发者ID:Qasemt,项目名称:NServiceKit,代码行数:10,代码来源:Cookies.cs
注:本文中的System.Net.Cookie类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论