I am using cookie for the authentication in web api. Creating cookies in the server side web api. and when i am reading it shows me null. also, i am sending a request using html ajax.
Function using to create cookie:
public HttpResponseMessage SetCookies()
{
var resp = new HttpResponseMessage()`enter code here`;
HttpClient client = new HttpClient(handler);
var cookie = new CookieHeaderValue("MyCookie", "12345");
cookie.Expires = DateTimeOffset.Now.AddDays(1);
cookie.Domain = Request.RequestUri.Host;
cookie.Path = "/";
resp.Headers.AddCookies(new CookieHeaderValue[] { cookie });
return resp;
}
after creating the cookies i try to reading cookie using below code:
CookieHeaderValue cookie = Request.Headers.GetCookies("MyCookie").FirstOrDefault();
if (cookie != null)
{
string sessionId = cookie["MyCookie"].Value;
}
it always returns null.
Please help me how to get and set the cookie value.
Thank you.
Here is the java script code :
function setCookie() {
var cname = " MyCookie";
var cvalue = "1234fer5678";
var exdays = 1;
var d = new Date();
d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
var expires = "expires=" + d.toUTCString();
document.cookie = cname + "=" + cvalue + "; " + expires;
}
function onButtonClick() {
setCookie();`enter code here`
$.ajax({
url: 'http://localhost:49702/v1/user/register',
type: "GET",
data: {},
dataType: 'json',
xhrFields: {
withCredentials: true
},
crossDomain: true
});
};
I set the cookies value manually. still i get the cookies in header request null on the server side api