ASP.NET Web Api:使用内存托管进行集成测试的身份验证

时间:2013-03-27 22:13:54

标签: asp.net-mvc asp.net-web-api asp.net-authentication

我正在尝试使用内存托管来集成测试我们的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;
        }
    }
}

1 个答案:

答案 0 :(得分:4)

为了记录最终有用的内容,我将以下行添加到我的CreateRequest方法

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

我不确定这是否是处理它的最佳方式,但它至少可以起作用。