I create a session middleware and want to test it. So I am using TestServer
for testing purpose.
The test code looks as follow:
using System.Linq;
using System.Threading.Tasks;
using ComponentsTest.StartUps;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.TestHost;
using NUnit.Framework;
namespace ComponentsTest.IntegrationTest
{
[TestFixture]
public class SessionMwTest
{
[SetUp]
public void Setup()
{
_server = new TestServer(_hostBuilder);
}
private readonly IWebHostBuilder _hostBuilder = new WebHostBuilder().UseStartup<StartUpSession>();
private TestServer _server;
[Test]
public async Task BrowserRequestForCookies_SeveralRequest_ExpectToken()
{
var client = _server.CreateClient();
var req1 = await client.GetAsync("/");
var sid = (from r in req1.Headers
where r.Key == "Set-Cookie"
from h in r.Value
where h.Contains("sid")
select h).FirstOrDefault();
StringAssert.Contains("sid", sid);
}
}
}
I want to make a request with the cookie, that I've got but do not know how to put the cookie to the request.
How can I do that?
Let's implement the Cookie Authentication in ASP.NET Core step by step. Open the Visual Studio and click on Create a new Project. Select ASP.NET Core Empty project and click on next. Give a name to your Project, select the location for the project creation, and click on Next.
By default, ASP.NET uses a non-persistent cookie to store the session state. However, if a user has disabled cookies on the browser, session state information cannot be stored in a cookie. ASP.NET offers an alternative in the form of cookieless sessions.
ASP.NET Cookie is a small bit of text that is used to store user-specific information. This information can be read by the web application whenever user visits the site. When a user requests for a web page, web server sends not just a page, but also a cookie containing the date and time.
At its most basic, a Cookie is simply a header. You could store the sid value of Set-Cookie
in a string and then for every request add the header:
request.Headers.Add("Cookie", new CookieHeaderValue(cookie.Name, cookie.Value).ToString());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With