Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-mvc/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/google-sheets/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Asp.net mvc 使用Asp.NETWebAPI和客户过滤器进行单元测试_Asp.net Mvc_Unit Testing_Authorize Attribute - Fatal编程技术网

Asp.net mvc 使用Asp.NETWebAPI和客户过滤器进行单元测试

Asp.net mvc 使用Asp.NETWebAPI和客户过滤器进行单元测试,asp.net-mvc,unit-testing,authorize-attribute,Asp.net Mvc,Unit Testing,Authorize Attribute,我正在Asp.NETMVCWebAPI中进行单元测试。 我有两个项目 1:Catalog.Api-包含所有控制器 2:Catalog.UnitTests-包含控制器的单元测试 所有控制器都使用“ApiController”继承,每个控制器都有自定义过滤器[AuthenticationFilter]。这是我的价值观控制器 [AuthenticationFilter] public class ValuesController : ApiController {

我正在Asp.NETMVCWebAPI中进行单元测试。 我有两个项目

1:Catalog.Api-包含所有控制器

2:Catalog.UnitTests-包含控制器的单元测试

所有控制器都使用“ApiController”继承,每个控制器都有自定义过滤器[AuthenticationFilter]。这是我的价值观控制器

    [AuthenticationFilter]
    public class ValuesController : ApiController
    {
        // GET api/values
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }

        // GET api/values/5
        public string Get(int id)
        {
            return "value";
        }

        // POST api/values
        public void Post([FromBody]string value)
        {
        }

        // PUT api/values/5
        public void Put(int id, [FromBody]string value)
        {
        }

        // DELETE api/values/5
        public void Delete(int id)
        {
        }
    }
现在在单元测试项目中,我有一个类和单元测试方法

        [TestMethod]
        public void CheckFilter()
        {
            try
            {
                var controller = new ValuesController();
                var controllerContext = new HttpControllerContext();
                var request = new HttpRequestMessage();
                request.Headers.Add("Authorization", "bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1bmlxdWVfbmFtZSI6InVhbGkiLCJlbWFpbCI6InVhbGlAaW5yZWFjaGNlLmNvbSIsIm5iZiI6MTU2NDY0NjIyMSwiZXhwI");

                controllerContext.Request = request;
                controller.ControllerContext = controllerContext;

                var result = controller.Get();
                Assert.IsTrue(result.Any());

            }
            catch (Exception ex)
            {
                Assert.Fail();
            }
        }
我通过将API项目的引用添加到我的单元测试项目中来调用我的控制器。因此,所有控制器都可以在单元测试项目中使用

问题是,当我调用values控制器时,它总是返回数据。当我删除请求和标头时,它也返回数据,但在这种情况下,这将是未经授权的


我想我的自定义筛选器没有调用。应该如何调用和验证用户。

我检查您的问题并配置该问题,基本上是您直接调用控制器。 基本上,控制器是一个类,当您调用它时,它的行为就像一个简单的类,调用方法并返回结果。它简单明了

但在您的情况下,您有api的项目,所以可以这样做

[TestMethod]
public void CheckFilter()
{
    try
    {
        var config = new HttpConfiguration();
        // This is the resgister method which is written in you Api project. That code is after this method this method because i did the same thing to call my controller.
        Catalog.Api.WebApiConfig.Register(config);
        using (var server = new HttpServer(config))
        {
            var client = new HttpClient(server);

            string url = "http://localhost:PortNumberOfProject/api/values";

            var request = new HttpRequestMessage
            {
                RequestUri = new Uri(url),
                Method = HttpMethod.Get
            };
            request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", "Your Token");

            var response = await client.SendAsync(request);
            Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
        }
    }
    catch (Exception ex)
    {
        Assert.Fail();
    }
}
下面是Api项目的WebApi注册方法,用于注册Api和路由

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.MapHttpAttributeRoutes();

        var cors = new EnableCorsAttribute("*", "*", "*");
        config.EnableCors(cors);

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}
这是你的控制器。现在调试测试并在[AuthenticationFilter]和OnAuthorization方法中添加断点

[AuthenticationFilter]
public class ValuesController : ApiController
{
    // GET api/values
    public IEnumerable<string> Get()
    {
        return new string[] { "value1", "value2" };
    }
}
[AuthenticationFilter]
公共类值控制器:ApiController
{
//获取api/值
公共IEnumerable Get()
{
返回新字符串[]{“value1”,“value2”};
}
}
[AuthenticationFilter]
public class ValuesController : ApiController
{
    // GET api/values
    public IEnumerable<string> Get()
    {
        return new string[] { "value1", "value2" };
    }
}