[英]Cannot access cookies set by Web Api Controller in MVC Controller
我通過HttpResponse在WebApi控制器中的服務器上設置了一些cookie。 但是,當我嘗試在我的MVC控制器中訪問這些cookie時,它們就消失了。 這些控制器在同一項目中。
Web Api控制器
[HttpPost]
public HttpResponseMessage Post([FromBody] string value)
{
HttpResponseMessage response = new HttpResponseMessage();
int width = 0;
Int32.TryParse(value, out width);
CookieHeaderValue cookieHeaderValue = null;
if (width < 768)
{
cookieHeaderValue = new CookieHeaderValue("device-type", "mobile");
}
else
{
cookieHeaderValue = new CookieHeaderValue("device-type", "non-mobile");
}
cookieHeaderValue.Expires = DateTimeOffset.Now.AddMinutes(30);
cookieHeaderValue.Domain = Request.RequestUri.Host;
cookieHeaderValue.Path = "/";
response.Headers.AddCookies(new CookieHeaderValue[] { cookieHeaderValue });
response.StatusCode = HttpStatusCode.OK;
return response;
}
MVC控制器
if (HttpContext.Response.Cookies["device-type"] != null &&
HttpContext.Response.Cookies["device-type"].ToString() == "mobile")
{
loggerwrapper.PickAndExecuteLogging("ordering cities");
region_LocationListings = region_LocationListings.OrderByDescending(r => r.locationlistings.Count).ToList();
}
CityListing.region_locationlist_dictionary[countryname.ToUpper()] = region_LocationListings;
設置您的cookie您將使用Response
public IHttpActionResult Post([FromBody] string value)
{
int width = 0;
Int32.TryParse(value, out width);
HttpCookie deviceType = new HttpCookie("device-type");
if (width < 768)
{
deviceType.Value = "mobile";
}
else
{
deviceType.Value = "non-mobile";
}
deviceType.Expires = DateTime.Now.AddMinutes(30);
deviceType.Domain = Request.RequestUri.Host;
deviceType.Path = "/";
HttpContext.Current.Response.Cookies.Add(deviceType);
return Ok();
}
要在控制器中獲取Cookie,應使用Request
Request.Cookies["device-type"]
不是響應對象
這就是我的工作方式
Web API控制器
[HttpPost]
public HttpResponseMessage Post([FromBody] string value)
{
int width = 0;
Int32.TryParse(value, out width);
string devicevalue = null;
if (width < 768)
{
devicevalue = "mobile";
}
else
{
devicevalue = "non-mobile";
}
var cookie = new CookieHeaderValue("device-type", devicevalue);
cookie.Expires = DateTime.Now.AddMinutes(30);
cookie.Domain = Request.RequestUri.Host;
cookie.Path = "/";
HttpResponseMessage response = new HttpResponseMessage();
response.Headers.AddCookies(new CookieHeaderValue[] { cookie });
return response;
}
MVC控制器
string devicetype = HttpContext.Request.Cookies["device-type"].Value;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.