Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET Core .NET Framework testing with cookie

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?

like image 694
softshipper Avatar asked Jul 22 '16 13:07

softshipper


People also ask

How do I use cookie authentication in .NET Core?

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.

Does ASP.NET use cookies?

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.

What is cookies in ASP.NET Core?

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.


1 Answers

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());
like image 110
nemec Avatar answered Sep 22 '22 07:09

nemec