I have created the cookie from another controller and I can see it present in the browser, and now Im trying read a Cookie in another Controller in my Project but the word Cookies in Request.Cookies["MyCookie"]; is underlined red with the error saying:
Error 5: 'System.Net.Http.HttpRequestMessage' does not contain a definition for 'Cookies' and no extension method 'Cookies' accepting a first argument of type 'System.Net.Http.HttpRequestMessage' could be found (are you missing a using directive or an assembly reference?)
Here is my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web;
using System.Security;
using System.Net.Http;
using System.Web.Http;
namespace Project.Controllers
{
public class UserController : ApiController
{
public String getCookie()
{
HttpCookie cookie = Request.Cookies["MyCookie"];
string username;
if( cookie != null)
{
username = Request.Cookies["MyCookie"].Value;
}
return username;
}
Im still new in C# .Net and I dont know how to solve this problem at all. Im using Visual Studio 2013. Can anyone help me, please?
Try this
string username="";
var cookie = Request.Headers.GetCookies("MyCookie").SingleOrDefault();
if (cookie != null)
{
username = cookie["MyCookie"].Value;
}
The System.Net.Http.HttpRequestMessage
object does not contain a cookies object. To access cookies in a WebAPI controller you need to look at the Request.Headers object like so:
CookieHeaderValue clientCookie =
Request.Headers.GetCookies("MyCookie").SingleOrDefault();
string username = clientCookie["MyCookie"].Value;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.