WCF WebHttpBinding support both http and https

Producer

//D:\C\WcfService6\WcfService6\Web.config
<?xml version="1.0"?>
<configuration>

  <appSettings>
    <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
  </appSettings>
  <system.web>
    <compilation debug="true" targetFramework="4.8" />
    <httpRuntime targetFramework="4.8"/>
  </system.web>
  <system.serviceModel>
      <bindings>
          <webHttpBinding>
              <binding name="WebHttpBinding_Http"
                       maxReceivedMessageSize="2147483647"
                       maxBufferSize="2147483647"
                       maxBufferPoolSize="2147483647">
                  <readerQuotas
                      maxDepth="2147483647"
                      maxArrayLength="2147483647"
                      maxStringContentLength="2147483647"
                      maxBytesPerRead="2147483647"
                      maxNameTableCharCount="2147483647"/>
                  <security mode="None"/>
              </binding>
              
              <binding name="WebHttpBinding_Https"
                       maxReceivedMessageSize="2147483647"
                       maxBufferSize="2147483647"
                       maxBufferPoolSize="2147483647">
                  <readerQuotas
                      maxDepth="2147483647"
                      maxArrayLength="2147483647"
                      maxStringContentLength="2147483647"
                      maxBytesPerRead="2147483647"
                      maxNameTableCharCount="2147483647"/>
                  <security mode="Transport"/>
              </binding>              
          </webHttpBinding>
      </bindings>

      <services>
          <service name="WcfService6.BookService">
              <endpoint address="rest"
                        binding="webHttpBinding"
                        bindingConfiguration="WebHttpBinding_Http"
                        contract="WcfService6.IBookService"
                        behaviorConfiguration="webBehavior">                  
              </endpoint>

              <endpoint address="rest"
                        binding="webHttpBinding"
                        bindingConfiguration="WebHttpBinding_Https"
                        contract="WcfService6.IBookService"
                        behaviorConfiguration="webBehavior">
              </endpoint>

              <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
          </service>
      </services>
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <!-- To avoid disclosing metadata information, set the values below to false before deployment -->
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
          <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
          <serviceDebug includeExceptionDetailInFaults="false"/>
          <dataContractSerializer maxItemsInObjectGraph="2147483647"/>
        </behavior>
      </serviceBehaviors>

        <endpointBehaviors>
            <behavior name="webBehavior">
                <webHttp/>
            </behavior>
        </endpointBehaviors>
    </behaviors>
    <protocolMapping>
        <add binding="basicHttpsBinding" scheme="https" />
    </protocolMapping>    
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
  </system.serviceModel>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
    <!--
        To browse web app root directory during debugging, set the value below to true.
        Set to false before deployment to avoid disclosing web app folder information.
      -->
    <directoryBrowse enabled="true"/>
      <security>
          <requestFiltering>
              <requestLimits maxAllowedContentLength="2147483647"/>
          </requestFiltering>
      </security>
  </system.webServer>

</configuration>


//D:\C\WcfService6\WcfService6\IBookService.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;

namespace WcfService6
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IBookService" in both code and config file together.
    [ServiceContract]
    public interface IBookService
    {
        [OperationContract]
        [WebGet(UriTemplate = "GetBooksListRest?cnt={cnt}",
            RequestFormat =WebMessageFormat.Json,
            ResponseFormat =WebMessageFormat.Json)]
        List<Book> GetBooksListRest(int cnt);
    }

    [DataContract]
    public class Book
    {
        [DataMember]
        public long Id { get; set; }

        [DataMember]
        public string Name { get; set;  }

        [DataMember]
        public string ISBN { get; set;  }

        [DataMember]
        public string Title { get; set;  }
    }
}


//D:\C\WcfService6\WcfService6\BookService.svc.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.Threading;

namespace WcfService6
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "BookService" in code, svc and config file together.
    // NOTE: In order to launch WCF Test Client for testing this service, please select BookService.svc or BookService.svc.cs at the Solution Explorer and start debugging.
    public class BookService : IBookService
    {
        private static long idx;
        private static long GetIncrementIdx()
        {
            return Interlocked.Increment(ref idx);
        }

        public List<Book> GetBooksListRest(int cnt)
        {
            List<Book> booksList = new List<Book>();
            for(int i=0;i<cnt;i++)
            {
                var a = GetIncrementIdx();
                booksList.Add(new Book()
                {
                    Id = a,
                    Name = $"Name_{a}",
                    ISBN = $"ISBN_{a}_{Guid.NewGuid():N}",
                    Title = $"Title_{a}"
                });
            }
            return booksList;
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.Threading;

namespace WcfService6
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "BookService" in code, svc and config file together.
    // NOTE: In order to launch WCF Test Client for testing this service, please select BookService.svc or BookService.svc.cs at the Solution Explorer and start debugging.
    public class BookService : IBookService
    {
        private static long idx;
        private static long GetIncrementIdx()
        {
            return Interlocked.Increment(ref idx);
        }

        public List<Book> GetBooksListRest(int cnt)
        {
            List<Book> booksList = new List<Book>();
            for(int i=0;i<cnt;i++)
            {
                var a = GetIncrementIdx();
                booksList.Add(new Book()
                {
                    Id = a,
                    Name = $"Name_{a}",
                    ISBN = $"ISBN_{a}_{Guid.NewGuid():N}",
                    Title = $"Title_{a}"
                });
            }
            return booksList;
        }
    }
}







 

//D:\C\WcfService6\WcfService6\WcfService6.csproj
<Project ToolsVersion="15.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
  <PropertyGroup>
    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
    <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
    <ProductVersion>
    </ProductVersion>
    <SchemaVersion>2.0</SchemaVersion>
    <ProjectGuid>{806ABEA3-FE41-4779-93A3-C67CE0C2EECF}</ProjectGuid>
    <ProjectTypeGuids>{349c5851-65df-11da-9384-00065b846f21};{fae04ec0-301f-11d3-bf4b-00c04f79efbc}</ProjectTypeGuids>
    <OutputType>Library</OutputType>
    <AppDesignerFolder>Properties</AppDesignerFolder>
    <RootNamespace>WcfService6</RootNamespace>
    <AssemblyName>WcfService6</AssemblyName>
    <TargetFrameworkVersion>v4.8</TargetFrameworkVersion>
    <WcfConfigValidationEnabled>True</WcfConfigValidationEnabled>
    <AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
    <UseIISExpress>true</UseIISExpress>
    <Use64BitIISExpress />
    <IISExpressSSLPort>44367</IISExpressSSLPort>
    <IISExpressAnonymousAuthentication>enabled</IISExpressAnonymousAuthentication>
    <IISExpressWindowsAuthentication>disabled</IISExpressWindowsAuthentication>
    <IISExpressUseClassicPipelineMode>false</IISExpressUseClassicPipelineMode>
    <UseGlobalApplicationHostFile />
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
    <DebugSymbols>true</DebugSymbols>
    <DebugType>full</DebugType>
    <Optimize>false</Optimize>
    <OutputPath>bin\</OutputPath>
    <DefineConstants>DEBUG;TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
    <DebugType>pdbonly</DebugType>
    <Optimize>true</Optimize>
    <OutputPath>bin\</OutputPath>
    <DefineConstants>TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
  </PropertyGroup>
  <ItemGroup>
    <Reference Include="Microsoft.CSharp" />
    <Reference Include="System.Web.DynamicData" />
    <Reference Include="System.Web.Entity" />
    <Reference Include="System.Web.ApplicationServices" />
    <Reference Include="System" />
    <Reference Include="System.Configuration" />
    <Reference Include="System.Core" />
    <Reference Include="System.Data" />
    <Reference Include="System.Drawing" />
    <Reference Include="System.EnterpriseServices" />
    <Reference Include="System.Runtime.Serialization" />
    <Reference Include="System.ServiceModel" />
    <Reference Include="System.ServiceModel.Web" />
    <Reference Include="System.Web" />
    <Reference Include="System.Web.Extensions" />
    <Reference Include="System.Web.Services" />
    <Reference Include="System.Xml" />
    <Reference Include="System.Xml.Linq" />
  </ItemGroup>
  <ItemGroup>
    <Content Include="BookService.svc" />
    <Content Include="Web.config" />
  </ItemGroup>
  <ItemGroup>
    <Compile Include="BookService.svc.cs">
      <DependentUpon>BookService.svc</DependentUpon>
    </Compile>
    <Compile Include="IBookService.cs" />
    <Compile Include="Properties\AssemblyInfo.cs" />
  </ItemGroup>
  <ItemGroup>
    <Folder Include="App_Data\" />
  </ItemGroup>
  <ItemGroup>
    <None Include="Web.Debug.config">
      <DependentUpon>Web.config</DependentUpon>
    </None>
    <None Include="Web.Release.config">
      <DependentUpon>Web.config</DependentUpon>
    </None>
  </ItemGroup>
  <PropertyGroup>
    <VisualStudioVersion Condition="'$(VisualStudioVersion)' == ''">10.0</VisualStudioVersion>
    <VSToolsPath Condition="'$(VSToolsPath)' == ''">$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)</VSToolsPath>
  </PropertyGroup>
  <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
  <Import Project="$(VSToolsPath)\WebApplications\Microsoft.WebApplication.targets" Condition="'$(VSToolsPath)' != ''" />
  <Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v10.0\WebApplications\Microsoft.WebApplication.targets" Condition="false" />
  <ProjectExtensions>
    <VisualStudio>
      <FlavorProperties GUID="{349c5851-65df-11da-9384-00065b846f21}">
        <WebProjectProperties>
          <UseIIS>True</UseIIS>
          <AutoAssignPort>True</AutoAssignPort>
          <DevelopmentServerPort>52841</DevelopmentServerPort>
          <DevelopmentServerVPath>/</DevelopmentServerVPath>
          <IISUrl>http://localhost:52841/</IISUrl>
          <NTLMAuthentication>False</NTLMAuthentication>
          <UseCustomServer>False</UseCustomServer>
          <CustomServerUrl>
          </CustomServerUrl>
          <SaveServerSettingsInUserFile>False</SaveServerSettingsInUserFile>
        </WebProjectProperties>
      </FlavorProperties>
    </VisualStudio>
  </ProjectExtensions>
  <!-- To modify your build process, add your task inside one of the targets below and uncomment it. 
       Other similar extension points exist, see Microsoft.Common.targets.
  <Target Name="BeforeBuild">
  </Target>
  <Target Name="AfterBuild">
  </Target>
  -->
</Project>

 

//D:\C\WcfService6\WcfService6\WcfService6.csproj

<UseIISExpress>true</UseIISExpress>
<Use64BitIISExpress />
<IISExpressSSLPort>44367</IISExpressSSLPort>

 

<WebProjectProperties>
<UseIIS>True</UseIIS>
<AutoAssignPort>True</AutoAssignPort>
<DevelopmentServerPort>52841</DevelopmentServerPort>
<DevelopmentServerVPath>/</DevelopmentServerVPath>
<IISUrl>http://localhost:52841/</IISUrl>
<NTLMAuthentication>False</NTLMAuthentication>
<UseCustomServer>False</UseCustomServer>
<CustomServerUrl>
</CustomServerUrl>
<SaveServerSettingsInUserFile>False</SaveServerSettingsInUserFile>
</WebProjectProperties>

 

 

 

Consumer

http://localhost:52841/BookService.svc/rest/GetBooksListRest?cnt=100

 

image

 

https://localhost:44367/BookService.svc/rest/GetBooksListRest?cnt=10000

 

 

 

 

 

 

image

 

using Newtonsoft.Json;
using System.Runtime.Serialization;

namespace ConsoleApp16
{
    internal class Program
    {
        static string httpUrl = @"http://localhost:52841/BookService.svc/rest/GetBooksListRest?cnt=1000000";
        static string httpsUrl = @"https://localhost:44367/BookService.svc/rest/GetBooksListRest?cnt=1000000";
        static HttpClient client;
        static void Main(string[] args)
        {
            client = new HttpClient();
            Task.Run(async () =>
            {
                await DownloadHttpsAsync();
            });
            Task.Run(async () =>
            {
                await DownloadHttpAsync();
            });
            Console.ReadLine();
        }

        static async Task DownloadHttpAsync(int batch=10)
        {
            Console.WriteLine($"Http url:{httpUrl}");
            for (int i = 0; i < 10; i++)
            {
                var jsonStr = await client.GetStringAsync(httpUrl);
                List<Book>? bksList = JsonConvert.DeserializeObject<List<Book>>(jsonStr);
                if (bksList != null && bksList.Any())
                {
                    Console.WriteLine($"Http Batch:{i + 1},First Id:{bksList.FirstOrDefault()?.Id},Last Id:{bksList.LastOrDefault()?.Id}");
                }
            }
        }

        static async Task DownloadHttpsAsync(int batch=10)
        {
            Console.WriteLine($"Https url:{httpsUrl}");
            for (int i=0;i<10;i++)
            {
               var jsonStr=await  client.GetStringAsync(httpsUrl);
                List<Book>? bksList = JsonConvert.DeserializeObject<List<Book>>(jsonStr);
                if (bksList != null && bksList.Any())
                {
                    Console.WriteLine($"Https Batch:{i + 1},First Id:{bksList.FirstOrDefault()?.Id},Last Id:{bksList.LastOrDefault()?.Id}");
                }
            }
        }
    }

    [DataContract]
    public class Book
    {
        [DataMember]
        public long Id { get; set; }

        [DataMember]
        public string Name { get; set; }

        [DataMember]
        public string ISBN { get; set; }

        [DataMember]
        public string Title { get; set; }
    }
}

 

 

 

 

Http url:http://localhost:52841/BookService.svc/rest/GetBooksListRest?cnt=1000000
Https url:https://localhost:44367/BookService.svc/rest/GetBooksListRest?cnt=1000000
Https Batch:1,First Id:15035260,Last Id:17011500
Http Batch:1,First Id:15011501,Last Id:16991433
Https Batch:2,First Id:17011501,Last Id:19007609
Http Batch:2,First Id:17012562,Last Id:19011500
Https Batch:3,First Id:19011501,Last Id:21002771
Http Batch:3,First Id:19020400,Last Id:21011500
Https Batch:4,First Id:21011501,Last Id:22973819
Http Batch:4,First Id:21039148,Last Id:23011500
Http Batch:5,First Id:23044014,Last Id:25011500
Https Batch:5,First Id:23011501,Last Id:24989425
Http Batch:6,First Id:25011501,Last Id:26988636
Https Batch:6,First Id:25031381,Last Id:27011500
Http Batch:7,First Id:27011501,Last Id:28893355
Https Batch:7,First Id:27130463,Last Id:29011500
Http Batch:8,First Id:29011501,Last Id:30933425
Https Batch:8,First Id:29096081,Last Id:31011500
Http Batch:9,First Id:31011501,Last Id:32864697
Https Batch:9,First Id:31160435,Last Id:33011500
Http Batch:10,First Id:33011501,Last Id:34858486
Https Batch:10,First Id:33164100,Last Id:35011500

 

 

image

 

posted @ 2026-05-16 19:12  FredGrit  阅读(8)  评论(0)    收藏  举报