Reputation: 34061
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?
Upvotes: 7
Views: 2994
Reputation: 1084
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());
Upvotes: 11
Reputation: 180
httprequest container might be helpful https://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.cookiecontainer(v=vs.110).aspx
WebRequest _webReq = WebRequest.Create( uri );
HttpWebRequest _httpReq = _webReq as HttpWebRequest;
_httpReq.CookieContainer.Add(cookie);
Upvotes: 0