本文整理汇总了C#中System.Web.HttpCookieCollection类的典型用法代码示例。如果您正苦于以下问题:C# HttpCookieCollection类的具体用法?C# HttpCookieCollection怎么用?C# HttpCookieCollection使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
HttpCookieCollection类属于System.Web命名空间,在下文中一共展示了HttpCookieCollection类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。
示例1: WhenRequestingMobileProfile_ThenJavascriptIsReturned
public void WhenRequestingMobileProfile_ThenJavascriptIsReturned()
{
_profileManifestRepository.Setup(p => p.GetProfile("generic"))
.Returns(new ProfileManifest
{
Id = "Generic-1.0",
Title = "Generic",
Features = new Feature[] {},
Version = "1.0"
});
_profileCookieEncoder.Setup(p => p.GetDeviceCapabilities(It.IsAny<HttpCookie>()))
.Returns(new Dictionary<string, string>{ {"id", "generic-1.0"} });
var controller = GetTestableMobileProfileController();
var response = Mock.Get(controller.Response);
var cookies = new HttpCookieCollection();
cookies.Add(new System.Web.HttpCookie("profile"));
controller.Request.SetHttpCookies(cookies);
var result = controller.ProfileScript();
Assert.IsType<PartialViewResult>(result);
response.VerifySet((r) => { r.ContentType = "text/javascript"; });
}
开发者ID:modulexcite,项目名称:reference-application,代码行数:27,代码来源:MobileProfileControllerFixture.cs
示例2: FakeHttpRequest
public FakeHttpRequest(string url, NameValueCollection formParams, NameValueCollection queryStringParams, HttpCookieCollection cookies)
{
_uri = new Uri(url);
_formParams = formParams;
_queryStringParams = queryStringParams;
_cookies = cookies;
}
开发者ID:haithemaraissia,项目名称:RentalMVCClean,代码行数:7,代码来源:FakeHttpRequest.cs
示例3: AddCookieData
/// <summary>
/// Adds cookie data to the request
/// </summary>
/// <param name="request">request to add cookiedata too</param>
/// <param name="cookieName">name of cookie to add data to</param>
/// <param name="key">key for data value</param>
/// <param name="value">value for data</param>
/// <returns>HttpRequestBase</returns>
/// <exception cref="ArgumentNullExeption">request is null</exception>
/// <exception cref="ArgumentNullExeption">cookieName is null or empty</exception>
/// <exception cref="ArgumentNullExeption">key is null or empty</exception>
/// <exception cref="ArgumentNullExeption">value is null</exception>
public static HttpRequestBase AddCookieData(this HttpRequestBase request, string cookieName, string key, string value)
{
if (request == null)
throw new ArgumentNullException("request");
if (String.IsNullOrWhiteSpace(cookieName))
throw new ArgumentNullException("cookieName");
if(String.IsNullOrWhiteSpace(key))
throw new ArgumentNullException("key");
if(value == null)
throw new ArgumentNullException("value");
if(request.Cookies == null)
{
var cookieCollection = new HttpCookieCollection();
Mock.Get(request).Setup(r => r.Cookies).Returns(cookieCollection);
}
if (!request.Cookies.AllKeys.Contains(cookieName))
request.Cookies.Add(new HttpCookie(cookieName));
request.Cookies[cookieName][key] = value;
return request;
}
开发者ID:AndyCC,项目名称:Jumbleblocks-website,代码行数:39,代码来源:HttpRequestHelper.cs
示例4: GetFakeContext
public static HttpContextBase GetFakeContext()
{
var httpContext = MockRepository.GenerateStub<HttpContextBase>();
var request = MockRepository.GenerateStub<HttpRequestBase>();
var response = MockRepository.GenerateStub<HttpResponseBase>();
var session = MockRepository.GenerateStub<HttpSessionStateBase>();
var server = MockRepository.GenerateStub<HttpServerUtilityBase>();
var cookies = new HttpCookieCollection();
httpContext.Stub(x => x.Request)
.Return(request);
httpContext.Stub(x => x.Response)
.Return(response);
httpContext.Stub(x => x.Session)
.Return(session);
httpContext.Stub(x => x.Server)
.Return(server);
response.Stub(x => x.Cookies)
.Return(cookies);
var writer = new StringWriter();
var wr = new SimpleWorkerRequest("", "", "", "", writer);
HttpContext.Current = new HttpContext(wr);
return httpContext;
}
开发者ID:stanacton,项目名称:ProductRegister,代码行数:26,代码来源:MockHttpContext.cs
示例5: Logout
public static void Logout(HttpCookieCollection requestCookies, HttpCookieCollection responseCookies)
{
FormsAuthentication.SignOut();
Thread.CurrentPrincipal = null;
HttpContext.Current.Session.Remove("EpiPrincipal");
ForgetLoggedInUser(requestCookies, responseCookies);
}
开发者ID:cocytus,项目名称:epidaurus,代码行数:7,代码来源:SecurityService.cs
示例6: DoesNothing
public void DoesNothing()
{
var responseCookies = new HttpCookieCollection();
var responseHeaders = new NameValueCollection();
var httpContext = Substitute.For<HttpContextBase>();
httpContext.Request.Headers.Returns(new NameValueCollection());
httpContext.Response.Cookies.Returns(responseCookies);
httpContext.Response.Headers.Returns(responseHeaders);
var controllerContext = new ControllerContext(
httpContext,
new RouteData(),
Substitute.For<ControllerBase>());
var filterContext = new ActionExecutedContext(
controllerContext,
Substitute.For<ActionDescriptor>(),
false,
null);
var attribute = new TurbolinksAttribute();
attribute.OnActionExecuted(filterContext);
Assert.Empty(responseCookies);
Assert.Empty(responseHeaders);
}
开发者ID:rajeshpillai,项目名称:aspnetmvcturbolinks,代码行数:30,代码来源:NoXhrRefererHeaderPresent.cs
示例7: OnlySetsRequestMethodCookie
public void OnlySetsRequestMethodCookie()
{
var responseCookies = new HttpCookieCollection();
var httpContext = Substitute.For<HttpContextBase>();
httpContext.Request.HttpMethod.Returns("GET");
httpContext.Request.Headers.Returns(
new NameValueCollection
{
{
"X-XHR-Referer",
"http://localhost:61049/Projects/Create"
}
});
httpContext.Response.Cookies.Returns(responseCookies);
var controllerContext = new ControllerContext(
httpContext,
new RouteData(),
Substitute.For<ControllerBase>());
var filterContext = new ActionExecutedContext(
controllerContext,
Substitute.For<ActionDescriptor>(),
false,
null);
var attribute = new TurbolinksAttribute();
attribute.OnActionExecuted(filterContext);
Assert.Equal("GET", responseCookies["request_method"].Value);
}
开发者ID:rajeshpillai,项目名称:aspnetmvcturbolinks,代码行数:35,代码来源:NoRedirection.cs
示例8: GetValueProvider
public void GetValueProvider()
{
// Arrange
HttpCookieCollection cookies = new HttpCookieCollection
{
new HttpCookie("foo", "fooValue"),
new HttpCookie("bar.baz", "barBazValue"),
new HttpCookie("", "emptyValue"),
new HttpCookie(null, "nullValue")
};
Mock<ControllerContext> mockControllerContext = new Mock<ControllerContext>();
mockControllerContext.Setup(o => o.HttpContext.Request.Cookies).Returns(cookies);
CookieValueProviderFactory factory = new CookieValueProviderFactory();
// Act
IValueProvider provider = factory.GetValueProvider(mockControllerContext.Object);
// Assert
Assert.Null(provider.GetValue(""));
Assert.True(provider.ContainsPrefix("bar"));
Assert.Equal("fooValue", provider.GetValue("foo").AttemptedValue);
Assert.Equal(CultureInfo.InvariantCulture, provider.GetValue("foo").Culture);
}
开发者ID:huangw-t,项目名称:aspnetwebstack,代码行数:25,代码来源:CookieValueProviderFactoryTest.cs
示例9: CreateContext
/// <summary>
/// Mocks the http context to test against
/// </summary>
/// <param name="fullUrl"></param>
/// <param name="routeData"></param>
/// <returns></returns>
private void CreateContext(Uri fullUrl, RouteData routeData = null)
{
//Request context
var requestContextMock = new Mock<RequestContext>();
RequestContext = requestContextMock.Object;
//Cookie collection
var cookieCollection = new HttpCookieCollection();
cookieCollection.Add(new HttpCookie("UMB_UCONTEXT", "FBA996E7-D6BE-489B-B199-2B0F3D2DD826"));
//Request
var requestMock = new Mock<HttpRequestBase>();
requestMock.Setup(x => x.AppRelativeCurrentExecutionFilePath).Returns("~" + fullUrl.AbsolutePath);
requestMock.Setup(x => x.PathInfo).Returns(string.Empty);
requestMock.Setup(x => x.RawUrl).Returns(VirtualPathUtility.ToAbsolute("~" + fullUrl.AbsolutePath, "/"));
requestMock.Setup(x => x.RequestContext).Returns(RequestContext);
requestMock.Setup(x => x.Url).Returns(fullUrl);
requestMock.Setup(x => x.ApplicationPath).Returns("/");
requestMock.Setup(x => x.Cookies).Returns(cookieCollection);
requestMock.Setup(x => x.ServerVariables).Returns(new NameValueCollection());
var queryStrings = HttpUtility.ParseQueryString(fullUrl.Query);
requestMock.Setup(x => x.QueryString).Returns(queryStrings);
requestMock.Setup(x => x.Form).Returns(new NameValueCollection());
//Cache
var cacheMock = new Mock<HttpCachePolicyBase>();
//Response
//var response = new FakeHttpResponse();
var responseMock = new Mock<HttpResponseBase>();
responseMock.Setup(x => x.ApplyAppPathModifier(It.IsAny<string>())).Returns((string s) => s);
responseMock.Setup(x => x.Cache).Returns(cacheMock.Object);
//Server
var serverMock = new Mock<HttpServerUtilityBase>();
serverMock.Setup(x => x.MapPath(It.IsAny<string>())).Returns(Environment.CurrentDirectory);
//HTTP Context
var httpContextMock = new Mock<HttpContextBase>();
httpContextMock.Setup(x => x.Cache).Returns(HttpRuntime.Cache);
httpContextMock.Setup(x => x.Items).Returns(new Dictionary<object, object>());
httpContextMock.Setup(x => x.Request).Returns(requestMock.Object);
httpContextMock.Setup(x => x.Server).Returns(serverMock.Object);
httpContextMock.Setup(x => x.Response).Returns(responseMock.Object);
HttpContext = httpContextMock.Object;
requestContextMock.Setup(x => x.HttpContext).Returns(httpContextMock.Object);
if (routeData != null)
{
requestContextMock.Setup(x => x.RouteData).Returns(routeData);
}
}
开发者ID:saciervo,项目名称:Umbraco-CMS,代码行数:66,代码来源:FakeHttpContextFactory.cs
示例10: FakeHttpRequest
public FakeHttpRequest(string url, bool isAuthenticated)
{
_url = new Uri(url);
_isAuthenticated = isAuthenticated;
_cookies = new HttpCookieCollection();
}
开发者ID:xlongtang,项目名称:nextra,代码行数:7,代码来源:FakeHttpRequest.cs
示例11: SetMockControllerContext
/// <summary>
/// allows access to things such as the controller's HttpContext, HttpContext.Request, HttpContext.Request.QueryString, HttpContext.Request.Cookies
/// </summary>
public static void SetMockControllerContext(this Controller yourController, HttpContextTestData httpContextTestData = null)
{
var request = new Mock<HttpRequestBase>();
var response = new Mock<HttpResponseBase>();
var requestQuery = httpContextTestData == null ? new NameValueCollection() : httpContextTestData.RequestQueryParams;
var reqCookies = new HttpCookieCollection();
var respCookies = new HttpCookieCollection();
// controller methods might access query params either as Request.QueryString or as Request["xxx"]
// make Request.QueryString work:
request.SetupGet(x => x.QueryString).Returns(requestQuery);
// make Request["xxx"] work:
if (requestQuery.Count > 0)
request.SetupGet(r => r[requestQuery.AllKeys[0]]).Returns(requestQuery.Get(0));
if (requestQuery.Count > 1)
request.SetupGet(r => r[requestQuery.AllKeys[1]]).Returns(requestQuery.Get(1));
if (requestQuery.Count > 2)
request.SetupGet(r => r[requestQuery.AllKeys[2]]).Returns(requestQuery.Get(2));
if (requestQuery.Count > 3)
request.SetupGet(r => r[requestQuery.AllKeys[3]]).Returns(requestQuery.Get(3));
if (requestQuery.Count > 4)
request.SetupGet(r => r[requestQuery.AllKeys[4]]).Returns(requestQuery.Get(4));
request.SetupGet(x => x.Cookies).Returns(reqCookies);
if (httpContextTestData != null && !string.IsNullOrEmpty(httpContextTestData.Url))
request.SetupGet(x => x.Url).Returns(new Uri(httpContextTestData.Url));
response.SetupGet(x => x.Cookies).Returns(respCookies);
var context = new Mock<HttpContextBase>();
context.SetupGet(x => x.Request).Returns(request.Object);
context.SetupGet(x => x.Response).Returns(response.Object);
if (httpContextTestData != null)
response.Setup(x => x.Redirect(It.IsAny<string>())).Callback<string>(url => httpContextTestData.RedirectUrl = url);
yourController.ControllerContext = new ControllerContext(context.Object, new RouteData(), yourController);
}
开发者ID:grbbod,项目名称:drconnect-jungo,代码行数:35,代码来源:TestControllerExtensions.cs
示例12: ProcessGet
internal string ProcessGet(SettingsClassHelper helper, HttpCookieCollection responseCookies)
{
var assembly = Assembly.GetExecutingAssembly();
var fileName = "{0}.Page.html".FormatWith(GetType().Namespace);
string fileContent;
using (var stream = assembly.GetManifestResourceStream(fileName))
{
if (stream == null)
throw new Exception("The UI can't be found.");
using (var reader = new StreamReader(stream))
fileContent = reader.ReadToEnd();
}
var model = new ViewModel
{
Settings = InflateSettingsViewModel(helper),
Token = CreateCsrfToken(responseCookies)
};
foreach (var item in Configuration.SettingsProvider.GetAllValues())
{
model.Settings.First(x => x.Name == item.Key).Value = item.Value;
}
var outputJson = new JavaScriptSerializer().Serialize(model);
fileContent = fileContent.Replace("{data}", outputJson);
return fileContent;
}
开发者ID:vondruska,项目名称:EasySettings,代码行数:33,代码来源:EasySettingsHandler.cs
示例13: RequestAuthenticationRedirectsToProviderWithReturnUrl
public void RequestAuthenticationRedirectsToProviderWithReturnUrl()
{
var cookies = new HttpCookieCollection();
// Arrange
var context = new Mock<HttpContextBase>();
context.Setup(c => c.Request.ServerVariables).Returns(new NameValueCollection());
context.Setup(c => c.Request.Url).Returns(new Uri("http://live.com/login.aspx"));
context.Setup(c => c.Request.RawUrl).Returns("/login.aspx");
context.Setup(c => c.Response.Cookies).Returns(cookies);
context.Setup(c => c.User.Identity.IsAuthenticated).Returns(false);
var client = new Mock<IAuthenticationClient>();
client.Setup(c => c.ProviderName).Returns("yahoo");
client.Setup(c => c.RequestAuthentication(
context.Object,
It.Is<Uri>(u => u.AbsoluteUri.StartsWith("http://yahoo.com/?__provider__=yahoo", StringComparison.OrdinalIgnoreCase))))
.Verifiable();
OAuthWebSecurity.RegisterClient(client.Object);
// Act
OAuthWebSecurity.RequestAuthenticationCore(context.Object, "yahoo", "http://yahoo.com");
// Assert
client.Verify();
}
开发者ID:richarddwelsh,项目名称:aspnetwebstack,代码行数:27,代码来源:OAuthWebSecurityTest.cs
示例14: GetAuthorizationCookie
public static string GetAuthorizationCookie(HttpCookieCollection cookies, string code, IBaseDb db)
{
//var code = request.QueryString["code"];
var stream = HttpTools.PostStream("https://oauth.yandex.ru/token",
string.Format("grant_type=authorization_code&code={0}&client_id={1}&client_secret={2}", code, ClientId, Password));
var model = SerializeTools.Deserialize<TokenModel>(stream);
var userCookie = new HttpCookie("yandex_token")
{
Value = model.access_token,
Expires = DateTime.Now.AddDays(30)
};
stream = HttpTools.PostStream(InfoUrl, string.Format("oauth_token={0}", userCookie.Value));
var email = SerializeTools.Deserialize<UserModel>(stream).default_email;
var user = db.SingleOrDefault<User>(u => u.Email == email);
cookies.Set(userCookie);
var rolesCookie = new HttpCookie("roles") {Value = string.Join(",", user.UserRoles.Select(r => r.Code)), Expires = DateTime.Now.AddDays(30)};
cookies.Set(rolesCookie);
return model.access_token;
}
开发者ID:torero-vlg,项目名称:docfis,代码行数:27,代码来源:YandexAuth.cs
示例15: RedirectToDifferentOrigin
public RedirectToDifferentOrigin()
{
var httpContext = Substitute.For<HttpContextBase>();
httpContext.Request.HttpMethod.Returns("GET");
httpContext.Request.Headers.Returns(
new NameValueCollection
{
{
"X-XHR-Referer",
"http://localhost:61049/Projects/Create"
}
});
responseCookies = new HttpCookieCollection();
httpContext.Response.Cookies.Returns(responseCookies);
var controllerContext = new ControllerContext(
httpContext,
new RouteData(),
Substitute.For<ControllerBase>());
filterContext = new ActionExecutedContext(
controllerContext,
Substitute.For<ActionDescriptor>(),
false,
null) { Result = new RedirectResult("http://google.com") };
var attribute = new TurbolinksAttribute();
attribute.OnActionExecuted(filterContext);
}
开发者ID:rajeshpillai,项目名称:aspnetmvcturbolinks,代码行数:32,代码来源:RedirectToDifferentOrigin.cs
示例16: RewriteContext
/// <summary>
/// Default constructor.
/// </summary>
/// <param name="engine">The rewriting engine.</param>
/// <param name="rawUrl">The initial, raw URL.</param>
/// <param name="httpMethod">The HTTP method used (GET, POST, ...)</param>
/// <param name="mapPath">The method to use for mapping paths.</param>
/// <param name="serverVariables">Collection of server variables.</param>
/// <param name="headers">Collection of headers.</param>
/// <param name="cookies">Collection of cookies.</param>
internal RewriteContext(RewriterEngine engine,
string rawUrl, string httpMethod,
MapPath mapPath,
NameValueCollection serverVariables,
NameValueCollection headers,
HttpCookieCollection cookies)
{
_engine = engine;
_location = rawUrl;
_method = httpMethod;
_mapPath = mapPath;
foreach (string key in serverVariables)
{
_properties.Add(key, serverVariables[key]);
}
foreach (string key in headers)
{
_properties.Add(key, headers[key]);
}
foreach (string key in cookies)
{
_properties.Add(key, cookies[key].Value);
}
}
开发者ID:bugjohnyang,项目名称:YAFNET,代码行数:37,代码来源:RewriteContext.cs
示例17: AuthenticateRequest_WithRequestHavingValidAuthCookies_SetsUserToGenericPrincipalWithRoles
public void AuthenticateRequest_WithRequestHavingValidAuthCookies_SetsUserToGenericPrincipalWithRoles()
{
// arrange
var module = new AuthenticationModule();
const string roles = "Admins|HostAdmins|Users";
var ticket = new FormsAuthenticationTicket(1, ".ASPXAUTH.42", DateTime.Now, DateTime.Now.AddDays(60), true,
roles);
string cookieValue = FormsAuthentication.Encrypt(ticket);
var authCookie = new HttpCookie(".ASPXAUTH.42") { Value = cookieValue };
var cookies = new HttpCookieCollection { authCookie };
var httpContext = new Mock<HttpContextBase>();
httpContext.Stub(c => c.User);
httpContext.Setup(c => c.Request.Path).Returns("/");
httpContext.Setup(c => c.Request.QueryString).Returns(new NameValueCollection());
httpContext.Setup(c => c.Request.Cookies).Returns(cookies);
httpContext.Setup(c => c.Response.Cookies).Returns(cookies);
var blogRequest = new BlogRequest("localhost", string.Empty, new Uri("http://localhost"), false,
RequestLocation.Blog, "/") { Blog = new Blog { Id = 42 } };
// act
module.AuthenticateRequest(httpContext.Object, blogRequest);
// assert
var principal = httpContext.Object.User as GenericPrincipal;
Assert.IsNotNull(principal);
Assert.IsTrue(principal.IsInRole("Admins"));
Assert.IsTrue(principal.IsInRole("HostAdmins"));
Assert.IsTrue(principal.IsInRole("Users"));
}
开发者ID:rhoadsce,项目名称:Subtext,代码行数:29,代码来源:AuthenticationModuleTests.cs
示例18: FakeHttpRequest
public FakeHttpRequest(string relativeUrl, string method, Uri url, Uri urlReferrer, NameValueCollection formParams, NameValueCollection queryStringParams,
HttpCookieCollection cookies)
: this(relativeUrl, method, formParams, queryStringParams, cookies)
{
_url = url;
_urlReferrer = urlReferrer;
}
开发者ID:cariarer,项目名称:TestStack.Seleno,代码行数:7,代码来源:FakeHttpRequest.cs
示例19: IsInDebugMode_ShouldBeCorrect
public void IsInDebugMode_ShouldBeCorrect(NameValueCollection queryString, HttpCookieCollection cookies, bool expected)
{
_mockRequest.Expect(r => r.QueryString).Return(queryString);
_mockRequest.Expect(r => r.Cookies).Return(cookies);
Assert.Equal(expected, _html.IsInDebugMode());
}
开发者ID:petemounce,项目名称:includecombiner,代码行数:7,代码来源:UtilityHtmlExtensionsFacts.cs
示例20: GetFakeHttpContext
public static HttpContextBase GetFakeHttpContext()
{
var context = new Mock<HttpContextBase>();
var request = new Mock<HttpRequestBase>();
var response = new Mock<HttpResponseBase>();
var responseCache = new Mock<HttpCachePolicyBase>();
var session = new Mock<HttpSessionStateBase>();
var server = new Mock<HttpServerUtilityBase>();
var cookie = new HttpCookieCollection();
var user = new Mock<IPrincipal>();
var identity = new Mock<IIdentity>();
request.Setup(req => req.Cookies).Returns(cookie);
response.Setup(resp => resp.Cookies).Returns(cookie);
identity.Setup(ident => ident.Name).Returns("kpratt");
user.Setup(usr => usr.Identity).Returns(identity.Object);
context.Setup(ctx => ctx.User).Returns(user.Object);
context.Setup(ctx => ctx.Request).Returns(request.Object);
context.Setup(ctx => ctx.Response).Returns(response.Object);
context.Setup(ctx => ctx.Response.Cache).Returns(responseCache.Object);
context.Setup(ctx => ctx.Session).Returns(session.Object);
context.Setup(ctx => ctx.Server).Returns(server.Object);
return context.Object;
}
开发者ID:Yavari,项目名称:MyFavourites,代码行数:26,代码来源:MvcMockHelper.cs
注:本文中的System.Web.HttpCookieCollection类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论