• WebApi单元测试记录


    一、MessageHandler不一定是全局的,也可以只应用到指定的Router上
    1、定义一个handler
    // Pipelines
    HttpMessageHandler affiliateShipmentsPipeline =
    HttpClientFactory.CreatePipeline(
    new HttpControllerDispatcher(config),
    new[] { new AffiliateShipmentsDispatcher() });
     
    2、将handler应用在指定的router上
    // Routes
    routes.MapHttpRoute(
    "AffiliateShipmentsHttpRoute",
    "api/affiliates/{key}/shipments/{shipmentKey}",
    defaults: new { controller = "AffiliateShipments", shipmentKey = RouteParameter.Optional },
    constraints: new { key = new GuidRouteConstraint(), shipmentKey = new GuidRouteConstraint() },
    handler: affiliateShipmentsPipeline);
     

     

    二、HttpRequest头添加Authorization信息
    HttpRequestMessage request = ConstructRequest(httpMethod, uri, mediaTypes);
    request.Headers.Authorization = new AuthenticationHeaderValue(
    "Basic",
    EncodeToBase64(
    string.Format("{0}:{1}", username, password)));
     
     
    private static string EncodeToBase64(string value) {
    byte[] toEncodeAsBytes = Encoding.UTF8.GetBytes(value);
    return Convert.ToBase64String(toEncodeAsBytes);
    }

     

    三、模拟异步发送Http请求
    internal static async Task<HttpResponseMessage> GetResponseAsync(
    HttpConfiguration config, HttpRequestMessage request) {
     
    using (var httpServer = new HttpServer(config))
    using (var client = HttpClientFactory.Create(innerHandler: httpServer)) {
     
    return await client.SendAsync(request);
    }
    }

     

    四、模拟WebApi HttpRequestMessage的Content
    request.Content = new ObjectContent<ShipmentRequestModel>(
    shipmentRequestModel, new System.Net.Http.Formatting.JsonMediaTypeFormatter());

     

     
    五、HttpRequestMessage对象获取依赖注入接口
    internal static class HttpRequestMessageExtensions {
     
    internal static IShipmentService GetShipmentService(this HttpRequestMessage request) {
     
    return request.GetServic e<IShipmentService>();
    }
     
    internal static IMembershipService GetMembershipService(this HttpRequestMessage request) {
     
    return request.GetService<IMembershipService>();
    }
     
    private static TService GetService<TService>(this HttpRequestMessage request) {
     
    IDependencyScope dependencyScope = request.GetDependencyScope();
    TService service = (TService)dependencyScope.GetService(typeof(TService));
     
    return service;
    }
    }
  • 相关阅读:
    freemarker的${!}
    什么是分布式消息中间件?
    Webservice工作原理及实例
    Nginx的一些基本功能
    dubbo与zookeeper的关系
    为什么推荐Zookeeper作注册中心
    ORACLE和MYSQL的简单区别
    SQL优化|Java面试题
    玩转 lua in Redis
    解决KafKa数据存储与顺序一致性保证
  • 原文地址:https://www.cnblogs.com/gossip/p/4512418.html
Copyright © 2020-2023  润新知