【问题标题】:ASP.NET Core .NET Framework testing with cookie使用 cookie 进行 ASP.NET Core .NET Framework 测试
【发布时间】:2016-11-26 10:08:53
【问题描述】:

我创建了一个会话中间件并想对其进行测试。所以我使用TestServer 进行测试。

测试代码如下:

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);

    }

  }
}

我想使用 cookie 发出请求,但我不知道如何将 cookie 放入请求中。
我该怎么做?

【问题讨论】:

    标签: c# asp.net cookies asp.net-core-mvc


    【解决方案1】:

    在最基本的情况下,Cookie 只是一个标头。您可以将Set-Cookie 的 sid 值存储在一个字符串中,然后为每个请求添加标头:

    request.Headers.Add("Cookie", new CookieHeaderValue(cookie.Name, cookie.Value).ToString());
    

    【讨论】:

      【解决方案2】:

      httprequest 容器可能会有所帮助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); 
      

      【讨论】:

      • TestServer 的实例包含一个请求,我必须在该对象中放置 cookie。您上面显示的代码不是基于 ASP.NET Core .NET Framework。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-06-28
      • 2017-10-12
      • 2016-10-07
      • 2020-12-10
      • 1970-01-01
      • 1970-01-01
      • 2017-09-02
      相关资源
      最近更新 更多