3

我正在尝试使用内存托管来集成测试我们的 web api 项目,但是在使用它时遇到了身份验证问题。我使用默认的 Web Api 模板和它创建的值控制器在一个基本的 Web Api 项目上重新创建了它。

我们正在使用 Autofac,因此也将其包含在测试中。我们还为 web api 使用 windows 身份验证,但出于测试的目的,这并不重要。

问题是测试中的“服务器”总是返回“此请求的授权已被拒绝”。

那么使用内存服务器进行授权的最佳方式是什么?我已经从另一个 stackoverflow 问题中注释掉了一些代码,但这似乎也不起作用。

using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using Autofac;
using Autofac.Integration.WebApi;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using WebApiTesting.Controllers;

namespace WebApiTesting.Tests.Controllers
{
    [TestClass]
    public class ValuesControllerTest
    {
        private const string URL = "http://test.testing.com/";
        private const string Username = "user";
        private const string Password = "supersecret";

        [TestMethod]
        public void InMemoryHosting()
        {
            var config = new HttpConfiguration();
            config.Routes.MapHttpRoute(name: "DefaultApi",
                                       routeTemplate: "api/{controller}/{id}",
                                       defaults: new {id = RouteParameter.Optional});
            config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;

            var server = new HttpServer(config);
            var builder = new ContainerBuilder();
            // Register API controllers using assembly scanning.
            builder.RegisterApiControllers(typeof(ValuesController).Assembly);
            var container = builder.Build();
            server.Configuration.DependencyResolver = new AutofacWebApiDependencyResolver(container);

            var client = new HttpClient(server);
            using (var request = CreateRequest("api/values", "application/json", HttpMethod.Get))
            {
                //Act
                using (HttpResponseMessage response = client.SendAsync(request).Result)
                {
                    // Assert
                    Assert.IsNotNull(response.Content);
                    Assert.AreEqual("application/json", response.Content.Headers.ContentType.MediaType);
                    var content = response.Content.ReadAsStringAsync().Result;
                    Assert.AreNotEqual("{\"Message\":\"Authorization has been denied for this request.\"}", content);
                }
            }
        }

        private HttpRequestMessage CreateRequest(string url, string mthv, HttpMethod method)
        {
            var request = new HttpRequestMessage { RequestUri = new Uri(URL + url) };
            /*byte[] toEncodeAsBytes = Encoding.UTF8.GetBytes(string.Format("{0}:{1}", Username, Password));
            request.Headers.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(toEncodeAsBytes));*/
            request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(mthv));
            request.Method = method;
            return request;
        }
    }
}
4

1 回答 1

4

只是为了记录最终的工作原理,我在我的 CreateRequest 方法中添加了以下行

Thread.CurrentPrincipal = new ClientRolePrincipal(new HttpListenerBasicIdentity(Username, Password));

我不确定这是否是处理它的最佳方法,但至少它确实有效。

于 2013-03-28T01:37:59.233 回答