HttpClient默认标头不能与Microsoft.Owin.Testing.TestServer一起使用

rya*_*lit 1 integration-testing owin katana asp.net-web-api2

我正在使用该Microsoft.Owin.Testing库集成测试我的API在内存中.我已经在OWIN JWT中间件中添加了我的身份验证需求,现在我正在尝试传递生成的令牌来测试需要授权的控制器的请求.我可以向您保证JWT中间件设置正确,因为它在正常使用时工作得很好.但是,我正在观察TestServer.HttpClient对象的一些奇怪行为.当我在HttpClient上设置默认授权头以传递令牌时,我的测试永远不会通过,因为无法识别令牌.但是,当我使用时TestServer.CreateRequest(...),测试正确传递并识别令牌.我更喜欢使用HttpClient方法,因为它们使用所提供的所有扩展方法使事情变得简单得多PostAsJsonAsync,等等.我开始认为在TestServer.HttpClient我或者我有一个完全缺少某些东西的错误.

这是我的测试类(使用NUnit3):

public class DefinitionsControllerTests
{
    private TestServer _server;
    private string _accessToken;

    [SetUp]
    public void Setup()
    {
        _server = TestServer.Create<Startup>();

        var credentials = new FormUrlEncodedContent(new[] {
            new KeyValuePair<string, string>("grant_type", "password"),
            new KeyValuePair<string, string>("username", "john.doe@mail.com"),
            new KeyValuePair<string, string>("password", "testing123")
        });

        // get token from OWIN JWT middleware
        dynamic resultBody = JObject.Parse(
            _server.HttpClient.PostAsync("/oauth/token", credentials).Result.Content.ReadAsStringAsync().Result);

        _accessToken = (string)resultBody.access_token;

        // this does not appear to ever work
        _server.HttpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _accessToken);
    }

    [TearDown]
    public void TearDown()
    {
        _server.Dispose();
    }

    [Test]
    public void GetById_WithExistingId()
    {
        // 401 Unauthorized response everytime and test fails
        var response = _server.HttpClient.GetAsync($"/api/definitions/{expected.Id}").Result;
        var actual = response.Content.ReadAsAsync<Definition>().Result;

        // 200 Ok every time and test passes
        // - these variables aren't part of the test but rather to show alternate request creation method that works
        var response2 = _server.CreateRequest($"/api/definitions/{expected.Id}")
            .AddHeader("Authorization", "Bearer " + _accessToken)
            .GetAsync()
            .Result;
        var actual2 = response.Content.ReadAsAsync<Definition>().Result;

        response.StatusCode.ShouldBe(HttpStatusCode.OK);
        actual.ShouldNotBeNull();
    }

    //...other test methods
}
Run Code Online (Sandbox Code Playgroud)

而我的控制器:

[Authorize]
public class DefinitionsController : ApiController
{
    private readonly IDefinitionRepository _repo;

    public DefinitionsController(IDefinitionRepository repo)
    {
        _repo = repo;
    }

    public IHttpActionResult Get(Guid id)
    {
        var definition = _repo.Get(id);

        if (definition == null)
            return NotFound();

        return Ok(definition);
    }
}
Run Code Online (Sandbox Code Playgroud)

任何人都知道为什么只有CreateRequest()有效?这有点令人愤怒.

Tra*_*her 5

问题是HttpClient属性每次都返回一个新实例.如果您保存该实例并重新使用它,它将起作用. https://github.com/aspnet/AspNetKatana/blob/b850cd8b4de61e65bbd7127ce02b5df7c4cb6db5/src/Microsoft.Owin.Testing/TestServer.cs#L48