无法访问由MVC控制器中的Web Api控制器设置的Cookie

时间:2018-12-28 19:16:23

标签: c# asp.net-mvc asp.net-web-api cookies

我通过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;

2 个答案:

答案 0 :(得分:0)

设置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"]不是响应对象

答案 1 :(得分:0)

这就是我的工作方式

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;