Jason
Jason

Reputation: 100

Can't set cookie in ASP.NET 5.0

I have been trying to set cookies for a users login info, but I keep getting these errors.

I am importing all of these

using System;

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;

// IDE says these are all unnessary
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Net.Http;
using System.Net.Http.Headers;
using Microsoft.AspNetCore.Http;

The code is this:

string token = Auth.password(username,password);

HttpCookie cookie = new HttpCookie("token",token);
cookie.Expires = DateTime.Now.AddDays(30);
Response.Cookies.Add(cookie);

And here are the errors

C:\xxx\my-server\Pages\Login.cshtml.cs(30,5): error CS0246: The type or namespace name 'HttpCookie' could not be found (are you missing a using directive or an assembly reference?) [C:\xxx\my-server\my-server.csproj]
C:\xxx\my-server\Pages\Login.cshtml.cs(30,29): error CS0246: The type or namespace name 'HttpCookie' could not be found (are you missing a using directive or an assembly reference?) [C:\xxx\my-server\my-server.csproj]
C:\xxx\my-server\Pages\Login.cshtml.cs(32,22): error CS1061: 'IResponseCookies' does not contain a definition for 'Add' and no accessible extension method 'Add' accepting a first argument of type 'IResponseCookies' could be found (are you missing a using directive or an assembly reference?) [C:\xxx\my-server\my-server.csproj]

I created the project using the command dotnet new razor.
I am using vscode.
The dotnet version is 5.0.301.

Upvotes: 0

Views: 3393

Answers (1)

Jason
Jason

Reputation: 100

The issue was solved by changing the code to:

string token = Auth.password(username,password);

HttpContext.Response.Cookies.Append("token", token, 
    new CookieOptions { Expires = DateTime.Now.AddDays(30) });

Upvotes: 1

Related Questions