• 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;
    }
    }
  • 相关阅读:
    136. Single Number
    125. Valid Palindrome
    122. Best Time to Buy and Sell Stock II
    121. Best Time to Buy and Sell Stock
    119. Pascal's Triangle II
    118. Pascal's Triangle
    集中式架构与分布式架构比较-copy
    分布式id产生-copy
    MySQL 5.7数据库参数优化-copy
    23个适合Java开发者的大数据工具和框架-copy
  • 原文地址:https://www.cnblogs.com/gossip/p/4512418.html
Copyright © 2020-2023  润新知