csharp 用于测试WebApi动作过滤器的助手类

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了csharp 用于测试WebApi动作过滤器的助手类相关的知识,希望对你有一定的参考价值。

internal static class ContextUtil
{
  public static HttpControllerContext CreateControllerContext(HttpConfiguration configuration = null, IHttpController instance = null, IHttpRouteData routeData = null, HttpRequestMessage request = null)
  {
      HttpConfiguration config = configuration ?? new HttpConfiguration();
      IHttpRouteData route = routeData ?? new HttpRouteData(new HttpRoute());
      HttpRequestMessage req = request ?? new HttpRequestMessage();
      req.SetConfiguration(config);
      req.SetRouteData(route);
  
      HttpControllerContext context = new HttpControllerContext(config, route, req);
      if (instance != null)
      {
          context.Controller = instance;
      }
      context.ControllerDescriptor = CreateControllerDescriptor(config);
  
      return context;
  }
  
  public static HttpActionContext CreateActionContext(HttpControllerContext controllerContext = null, HttpActionDescriptor actionDescriptor = null)
  {
      HttpControllerContext context = controllerContext ?? ContextUtil.CreateControllerContext();
      HttpActionDescriptor descriptor = actionDescriptor ?? CreateActionDescriptor();
      descriptor.ControllerDescriptor = context.ControllerDescriptor;
      return new HttpActionContext(context, descriptor);
  }
  
  public static HttpActionContext GetHttpActionContext(HttpRequestMessage request)
  {
      HttpActionContext actionContext = CreateActionContext();
      actionContext.ControllerContext.Request = request;
      return actionContext;
  }
  
  public static HttpActionExecutedContext GetActionExecutedContext(HttpRequestMessage request, HttpResponseMessage response)
  {
      HttpActionContext actionContext = CreateActionContext();
      actionContext.ControllerContext.Request = request;
      HttpActionExecutedContext actionExecutedContext = new HttpActionExecutedContext(actionContext, null) { Response = response };
      return actionExecutedContext;
  }
  
  public static HttpControllerDescriptor CreateControllerDescriptor(HttpConfiguration config = null)
  {
      if (config == null)
      {
          config = new HttpConfiguration();
      }
      return new HttpControllerDescriptor() { Configuration = config, ControllerName = "FooController" };
  }
  
  public static HttpActionDescriptor CreateActionDescriptor()
  {
      var mock = new Mock<HttpActionDescriptor>() { CallBase = true };
      mock.SetupGet(d => d.ActionName).Returns("Bar");
      return mock.Object;
  }
}

以上是关于csharp 用于测试WebApi动作过滤器的助手类的主要内容,如果未能解决你的问题,请参考以下文章

csharp IP地址限制动作过滤器

csharp ASP.net MVC3的程序化GZip动作过滤器

csharp ASP.NET的助手,ASP.NET MVC应用服务器端测试

csharp 用C#编写的简单SMTP邮件客户端助手类,用于异步发送电子邮件。注意:使用Log4Net进行日志记录。

PHPUnit 测试中 Yii2 中的模拟视图助手

csharp Umbraco安装包动作,向仪表板添加新的“选项卡”(不是“部分”)。用于:https://github.com/EndzoneSoftware/uWhiteL