本文整理汇总了C#中System.Web.HttpCookieCollection类的典型用法代码示例。如果您正苦于以下问题:C# HttpCookieCollection类的具体用法?C# HttpCookieCollection怎么用?C# HttpCookieCollection使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
HttpCookieCollection类属于System.Web命名空间,在下文中一共展示了HttpCookieCollection类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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"; });
}
示例2: FakeHttpRequest
public FakeHttpRequest(string url, NameValueCollection formParams, NameValueCollection queryStringParams, HttpCookieCollection cookies)
{
_uri = new Uri(url);
_formParams = formParams;
_queryStringParams = queryStringParams;
_cookies = cookies;
}
示例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;
}
示例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;
}
示例5: Logout
public static void Logout(HttpCookieCollection requestCookies, HttpCookieCollection responseCookies)
{
FormsAuthentication.SignOut();
Thread.CurrentPrincipal = null;
HttpContext.Current.Session.Remove("EpiPrincipal");
ForgetLoggedInUser(requestCookies, responseCookies);
}
示例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);
}
示例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);
}
示例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);
}
示例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);
}
}
示例10: FakeHttpRequest
public FakeHttpRequest(string url, bool isAuthenticated)
{
_url = new Uri(url);
_isAuthenticated = isAuthenticated;
_cookies = new HttpCookieCollection();
}
示例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);
}
示例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;
}
示例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();
}
示例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;
}
示例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);
}