├── .gitignore ├── LICENSE ├── README.md ├── appveyor.yml └── src ├── WcfCoreMtomEncoder.sln ├── WcfCoreMtomEncoder.sln.DotSettings └── WcfCoreMtomEncoder ├── MtomMessageEncoder.cs ├── MtomMessageEncoderBindingElement.cs ├── MtomMessageEncoderFactory.cs ├── MtomPart.cs └── WcfCoreMtomEncoder.csproj /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.rsuser 8 | *.suo 9 | *.user 10 | *.userosscache 11 | *.sln.docstates 12 | 13 | # User-specific files (MonoDevelop/Xamarin Studio) 14 | *.userprefs 15 | 16 | # Build results 17 | [Dd]ebug/ 18 | [Dd]ebugPublic/ 19 | [Rr]elease/ 20 | [Rr]eleases/ 21 | x64/ 22 | x86/ 23 | [Aa][Rr][Mm]/ 24 | [Aa][Rr][Mm]64/ 25 | bld/ 26 | [Bb]in/ 27 | [Oo]bj/ 28 | [Ll]og/ 29 | 30 | # Visual Studio 2015/2017 cache/options directory 31 | .vs/ 32 | # Uncomment if you have tasks that create the project's static files in wwwroot 33 | #wwwroot/ 34 | 35 | # Visual Studio 2017 auto generated files 36 | Generated\ Files/ 37 | 38 | # MSTest test Results 39 | [Tt]est[Rr]esult*/ 40 | [Bb]uild[Ll]og.* 41 | 42 | # NUNIT 43 | *.VisualState.xml 44 | TestResult.xml 45 | 46 | # Build Results of an ATL Project 47 | [Dd]ebugPS/ 48 | [Rr]eleasePS/ 49 | dlldata.c 50 | 51 | # Benchmark Results 52 | BenchmarkDotNet.Artifacts/ 53 | 54 | # .NET Core 55 | project.lock.json 56 | project.fragment.lock.json 57 | artifacts/ 58 | 59 | # StyleCop 60 | StyleCopReport.xml 61 | 62 | # Files built by Visual Studio 63 | *_i.c 64 | *_p.c 65 | *_h.h 66 | *.ilk 67 | *.meta 68 | *.obj 69 | *.iobj 70 | *.pch 71 | *.pdb 72 | *.ipdb 73 | *.pgc 74 | *.pgd 75 | *.rsp 76 | *.sbr 77 | *.tlb 78 | *.tli 79 | *.tlh 80 | *.tmp 81 | *.tmp_proj 82 | *_wpftmp.csproj 83 | *.log 84 | *.vspscc 85 | *.vssscc 86 | .builds 87 | *.pidb 88 | *.svclog 89 | *.scc 90 | 91 | # Chutzpah Test files 92 | _Chutzpah* 93 | 94 | # Visual C++ cache files 95 | ipch/ 96 | *.aps 97 | *.ncb 98 | *.opendb 99 | *.opensdf 100 | *.sdf 101 | *.cachefile 102 | *.VC.db 103 | *.VC.VC.opendb 104 | 105 | # Visual Studio profiler 106 | *.psess 107 | *.vsp 108 | *.vspx 109 | *.sap 110 | 111 | # Visual Studio Trace Files 112 | *.e2e 113 | 114 | # TFS 2012 Local Workspace 115 | $tf/ 116 | 117 | # Guidance Automation Toolkit 118 | *.gpState 119 | 120 | # ReSharper is a .NET coding add-in 121 | _ReSharper*/ 122 | *.[Rr]e[Ss]harper 123 | *.DotSettings.user 124 | 125 | # JustCode is a .NET coding add-in 126 | .JustCode 127 | 128 | # TeamCity is a build add-in 129 | _TeamCity* 130 | 131 | # DotCover is a Code Coverage Tool 132 | *.dotCover 133 | 134 | # AxoCover is a Code Coverage Tool 135 | .axoCover/* 136 | !.axoCover/settings.json 137 | 138 | # Visual Studio code coverage results 139 | *.coverage 140 | *.coveragexml 141 | 142 | # NCrunch 143 | _NCrunch_* 144 | .*crunch*.local.xml 145 | nCrunchTemp_* 146 | 147 | # MightyMoose 148 | *.mm.* 149 | AutoTest.Net/ 150 | 151 | # Web workbench (sass) 152 | .sass-cache/ 153 | 154 | # Installshield output folder 155 | [Ee]xpress/ 156 | 157 | # DocProject is a documentation generator add-in 158 | DocProject/buildhelp/ 159 | DocProject/Help/*.HxT 160 | DocProject/Help/*.HxC 161 | DocProject/Help/*.hhc 162 | DocProject/Help/*.hhk 163 | DocProject/Help/*.hhp 164 | DocProject/Help/Html2 165 | DocProject/Help/html 166 | 167 | # Click-Once directory 168 | publish/ 169 | 170 | # Publish Web Output 171 | *.[Pp]ublish.xml 172 | *.azurePubxml 173 | # Note: Comment the next line if you want to checkin your web deploy settings, 174 | # but database connection strings (with potential passwords) will be unencrypted 175 | *.pubxml 176 | *.publishproj 177 | 178 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 179 | # checkin your Azure Web App publish settings, but sensitive information contained 180 | # in these scripts will be unencrypted 181 | PublishScripts/ 182 | 183 | # NuGet Packages 184 | *.nupkg 185 | # The packages folder can be ignored because of Package Restore 186 | **/[Pp]ackages/* 187 | # except build/, which is used as an MSBuild target. 188 | !**/[Pp]ackages/build/ 189 | # Uncomment if necessary however generally it will be regenerated when needed 190 | #!**/[Pp]ackages/repositories.config 191 | # NuGet v3's project.json files produces more ignorable files 192 | *.nuget.props 193 | *.nuget.targets 194 | 195 | # Microsoft Azure Build Output 196 | csx/ 197 | *.build.csdef 198 | 199 | # Microsoft Azure Emulator 200 | ecf/ 201 | rcf/ 202 | 203 | # Windows Store app package directories and files 204 | AppPackages/ 205 | BundleArtifacts/ 206 | Package.StoreAssociation.xml 207 | _pkginfo.txt 208 | *.appx 209 | 210 | # Visual Studio cache files 211 | # files ending in .cache can be ignored 212 | *.[Cc]ache 213 | # but keep track of directories ending in .cache 214 | !?*.[Cc]ache/ 215 | 216 | # Others 217 | ClientBin/ 218 | ~$* 219 | *~ 220 | *.dbmdl 221 | *.dbproj.schemaview 222 | *.jfm 223 | *.pfx 224 | *.publishsettings 225 | orleans.codegen.cs 226 | 227 | # Including strong name files can present a security risk 228 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 229 | #*.snk 230 | 231 | # Since there are multiple workflows, uncomment next line to ignore bower_components 232 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 233 | #bower_components/ 234 | 235 | # RIA/Silverlight projects 236 | Generated_Code/ 237 | 238 | # Backup & report files from converting an old project file 239 | # to a newer Visual Studio version. Backup files are not needed, 240 | # because we have git ;-) 241 | _UpgradeReport_Files/ 242 | Backup*/ 243 | UpgradeLog*.XML 244 | UpgradeLog*.htm 245 | ServiceFabricBackup/ 246 | *.rptproj.bak 247 | 248 | # SQL Server files 249 | *.mdf 250 | *.ldf 251 | *.ndf 252 | 253 | # Business Intelligence projects 254 | *.rdl.data 255 | *.bim.layout 256 | *.bim_*.settings 257 | *.rptproj.rsuser 258 | *- Backup*.rdl 259 | 260 | # Microsoft Fakes 261 | FakesAssemblies/ 262 | 263 | # GhostDoc plugin setting file 264 | *.GhostDoc.xml 265 | 266 | # Node.js Tools for Visual Studio 267 | .ntvs_analysis.dat 268 | node_modules/ 269 | 270 | # Visual Studio 6 build log 271 | *.plg 272 | 273 | # Visual Studio 6 workspace options file 274 | *.opt 275 | 276 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 277 | *.vbw 278 | 279 | # Visual Studio LightSwitch build output 280 | **/*.HTMLClient/GeneratedArtifacts 281 | **/*.DesktopClient/GeneratedArtifacts 282 | **/*.DesktopClient/ModelManifest.xml 283 | **/*.Server/GeneratedArtifacts 284 | **/*.Server/ModelManifest.xml 285 | _Pvt_Extensions 286 | 287 | # Paket dependency manager 288 | .paket/paket.exe 289 | paket-files/ 290 | 291 | # FAKE - F# Make 292 | .fake/ 293 | 294 | # JetBrains Rider 295 | .idea/ 296 | *.sln.iml 297 | 298 | # CodeRush personal settings 299 | .cr/personal 300 | 301 | # Python Tools for Visual Studio (PTVS) 302 | __pycache__/ 303 | *.pyc 304 | 305 | # Cake - Uncomment if you are using it 306 | # tools/** 307 | # !tools/packages.config 308 | 309 | # Tabs Studio 310 | *.tss 311 | 312 | # Telerik's JustMock configuration file 313 | *.jmconfig 314 | 315 | # BizTalk build output 316 | *.btp.cs 317 | *.btm.cs 318 | *.odx.cs 319 | *.xsd.cs 320 | 321 | # OpenCover UI analysis results 322 | OpenCover/ 323 | 324 | # Azure Stream Analytics local run output 325 | ASALocalRun/ 326 | 327 | # MSBuild Binary and Structured Log 328 | *.binlog 329 | 330 | # NVidia Nsight GPU debugger configuration file 331 | *.nvuser 332 | 333 | # MFractors (Xamarin productivity tool) working folder 334 | .mfractor/ 335 | 336 | # Local History for Visual Studio 337 | .localhistory/ 338 | 339 | # BeatPulse healthcheck temp database 340 | healthchecksdb -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2019 Lenny Kean 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # WcfCoreMtomEncoder 2 | 3 | Currently, .NET Core WCF has no build-in support MTOM. 4 | 5 | The `MtomMessageEncoderBindingElement` allows .NET Core applications to communicate with WCF endpoints which support MTOM encoding. 6 | 7 | **Note:** This is _not_ a complete implementation of MTOM. It is meant as a workaround for calling existing MTOM encoded SOAP services. It consumes MTOM encoded messages, but does not perform MTOMEncoding on outbound messages. However this should be sufficent for interoperating with existing services. 8 | 9 | [![Build status](https://ci.appveyor.com/api/projects/status/v4836gx8j9f0a8gd?svg=true)](https://ci.appveyor.com/project/lennykean/wcfcoremtomencoder) 10 | [![NuGet](https://img.shields.io/nuget/v/WcfCoreMtomEncoder.svg)](https://www.nuget.org/packages/WcfCoreMtomEncoder/) 11 | 12 | ### Installation 13 | 14 | #### .NET CLI 15 | ```shell 16 | > dotnet add package WcfCoreMtomEncoder 17 | ``` 18 | #### Package Manager 19 | ```shell 20 | PM> Install-Package WcfCoreMtomEncoder 21 | ``` 22 | 23 | ## Usage 24 | 25 | The `MtomMessageEncoderBindingElement` is meant to wrap another message encoder, usually `TextMessageEncodingBindingElement`. 26 | 27 | ### Creating a custom binding 28 | 29 | ```csharp 30 | var encoding = new MtomMessageEncoderBindingElement(new TextMessageEncodingBindingElement()); 31 | var transport = new HttpTransportBindingElement(); 32 | var customBinding = new CustomBinding(encoding, transport); 33 | 34 | var client = new MtomEnabledServiceClient(customBinding); 35 | ``` 36 | -------------------------------------------------------------------------------- /appveyor.yml: -------------------------------------------------------------------------------- 1 | version: 0.1.{build} 2 | branches: 3 | only: 4 | - master 5 | 6 | image: 7 | - Visual Studio 2017 8 | 9 | dotnet_csproj: 10 | patch: true 11 | file: '**\*.csproj' 12 | version: '{version}' 13 | package_version: '{version}' 14 | assembly_version: '{version}' 15 | file_version: '{version}' 16 | informational_version: '{version}' 17 | 18 | before_build: 19 | - dotnet restore src 20 | 21 | build: 22 | project: src/WcfCoreMtomEncoder.sln 23 | verbosity: minimal 24 | 25 | artifacts: 26 | - path: '**\*.nupkg' 27 | 28 | deploy: 29 | - provider: NuGet 30 | api_key: 31 | secure: TxIbRI8gvs1+zTXwRqlf67ocgcebFSPZL22T0GqtmeLhlw/Yhig13VDpsuiToydc 32 | artifact: /.*\.nupkg/ 33 | -------------------------------------------------------------------------------- /src/WcfCoreMtomEncoder.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 16 4 | VisualStudioVersion = 16.0.28803.156 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "WcfCoreMtomEncoder", "WcfCoreMtomEncoder\WcfCoreMtomEncoder.csproj", "{F5F35855-99CB-44E0-9471-BC8BDE86B555}" 7 | EndProject 8 | Global 9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 10 | Debug|Any CPU = Debug|Any CPU 11 | Release|Any CPU = Release|Any CPU 12 | EndGlobalSection 13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 14 | {F5F35855-99CB-44E0-9471-BC8BDE86B555}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 15 | {F5F35855-99CB-44E0-9471-BC8BDE86B555}.Debug|Any CPU.Build.0 = Debug|Any CPU 16 | {F5F35855-99CB-44E0-9471-BC8BDE86B555}.Release|Any CPU.ActiveCfg = Release|Any CPU 17 | {F5F35855-99CB-44E0-9471-BC8BDE86B555}.Release|Any CPU.Build.0 = Release|Any CPU 18 | EndGlobalSection 19 | GlobalSection(SolutionProperties) = preSolution 20 | HideSolutionNode = FALSE 21 | EndGlobalSection 22 | GlobalSection(ExtensibilityGlobals) = postSolution 23 | SolutionGuid = {7C1E310A-8874-4830-81D5-1447F4E7EB17} 24 | EndGlobalSection 25 | EndGlobal 26 | -------------------------------------------------------------------------------- /src/WcfCoreMtomEncoder.sln.DotSettings: -------------------------------------------------------------------------------- 1 |  2 | True -------------------------------------------------------------------------------- /src/WcfCoreMtomEncoder/MtomMessageEncoder.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.IO; 4 | using System.Linq; 5 | using System.Net.Http; 6 | using System.Net.Http.Headers; 7 | using System.Net.Mime; 8 | using System.ServiceModel.Channels; 9 | using System.Text; 10 | using System.Text.RegularExpressions; 11 | using System.Xml.Linq; 12 | 13 | namespace WcfCoreMtomEncoder 14 | { 15 | public class MtomMessageEncoder : MessageEncoder 16 | { 17 | private readonly MessageEncoder _innerEncoder; 18 | 19 | public MtomMessageEncoder(MessageEncoder innerEncoder) 20 | { 21 | _innerEncoder = innerEncoder; 22 | } 23 | 24 | public override string ContentType => _innerEncoder.ContentType; 25 | public override string MediaType => _innerEncoder.MediaType; 26 | public override MessageVersion MessageVersion => _innerEncoder.MessageVersion; 27 | 28 | public override Message ReadMessage(ArraySegment buffer, BufferManager bufferManager, string contentType) 29 | { 30 | using (var stream = new MemoryStream(buffer.ToArray())) 31 | { 32 | var message = ReadMessage(stream, 1024, contentType); 33 | bufferManager.ReturnBuffer(buffer.Array); 34 | return message; 35 | } 36 | } 37 | 38 | public override Message ReadMessage(Stream stream, int maxSizeOfHeaders, string contentType) 39 | { 40 | if (_innerEncoder.IsContentTypeSupported(contentType)) 41 | { 42 | var memStream = new MemoryStream(); // We need an non disposed stream 43 | stream.CopyTo(memStream); 44 | memStream.Seek(0, SeekOrigin.Begin); 45 | return _innerEncoder.ReadMessage(memStream, maxSizeOfHeaders, contentType); 46 | } 47 | else 48 | { 49 | var parts = ( 50 | from p in GetMultipartContent(stream, contentType) 51 | select new MtomPart(p)).ToList(); 52 | 53 | var mainPart = ( 54 | from part in parts 55 | where part.ContentId == new ContentType(contentType).Parameters?["start"] 56 | select part).SingleOrDefault() ?? parts.First(); 57 | 58 | var mainContent = ResolveRefs(mainPart.GetStringContentForEncoder(_innerEncoder), parts); 59 | var mainContentStream = CreateStream(mainContent, mainPart.ContentType); 60 | 61 | return _innerEncoder.ReadMessage(mainContentStream, maxSizeOfHeaders, mainPart.ContentType.ToString()); 62 | } 63 | } 64 | 65 | public override ArraySegment WriteMessage(Message message, int maxMessageSize, BufferManager bufferManager, int messageOffset) 66 | { 67 | return _innerEncoder.WriteMessage(message, maxMessageSize, bufferManager, messageOffset); 68 | } 69 | 70 | public override void WriteMessage(Message message, Stream stream) 71 | { 72 | _innerEncoder.WriteMessage(message, stream); 73 | } 74 | 75 | public override bool IsContentTypeSupported(string contentType) 76 | { 77 | if (_innerEncoder.IsContentTypeSupported(contentType)) 78 | return true; 79 | 80 | var contentTypes = contentType.Split(';').Select(c => c.Trim()).ToList(); 81 | 82 | if (contentTypes.Contains("multipart/related", StringComparer.OrdinalIgnoreCase) && 83 | contentTypes.Contains("type=\"application/xop+xml\"", StringComparer.OrdinalIgnoreCase)) 84 | { 85 | return true; 86 | } 87 | return false; 88 | } 89 | 90 | public override T GetProperty() 91 | { 92 | return _innerEncoder.GetProperty(); 93 | } 94 | 95 | private static IEnumerable GetMultipartContent(Stream stream, string contentType) 96 | { 97 | var content = new StreamContent(stream); 98 | 99 | content.Headers.Add("Content-Type", contentType); 100 | 101 | return content.ReadAsMultipartAsync().Result.Contents; 102 | } 103 | 104 | private static string ResolveRefs(string mainContent, IList parts) 105 | { 106 | bool ReferenceMatch(XAttribute hrefAttr, MtomPart part) 107 | { 108 | var partId = Regex.Match(part.ContentId, "<(?.*)>"); 109 | var href = Regex.Match(hrefAttr.Value, "cid:(?.*)"); 110 | 111 | return href.Groups["uri"].Value == partId.Groups["uri"].Value; 112 | } 113 | 114 | var doc = XDocument.Parse(mainContent); 115 | var references = doc.Descendants(XName.Get("Include", "http://www.w3.org/2004/08/xop/include")).ToList(); 116 | 117 | foreach (var reference in references) 118 | { 119 | var referencedPart = ( 120 | from part in parts 121 | where ReferenceMatch(reference.Attribute("href"), part) 122 | select part).Single(); 123 | 124 | reference.ReplaceWith(Convert.ToBase64String(referencedPart.GetRawContent())); 125 | } 126 | return doc.ToString(SaveOptions.DisableFormatting); 127 | } 128 | 129 | private static Stream CreateStream(string content, MediaTypeHeaderValue contentType) 130 | { 131 | var encoding = !string.IsNullOrEmpty(contentType.CharSet) 132 | ? Encoding.GetEncoding(contentType.CharSet) 133 | : Encoding.Default; 134 | 135 | return new MemoryStream(encoding.GetBytes(content)); 136 | } 137 | } 138 | } 139 | -------------------------------------------------------------------------------- /src/WcfCoreMtomEncoder/MtomMessageEncoderBindingElement.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.ServiceModel.Channels; 3 | 4 | namespace WcfCoreMtomEncoder 5 | { 6 | public class MtomMessageEncoderBindingElement : MessageEncodingBindingElement 7 | { 8 | private readonly MessageEncodingBindingElement _innerEncodingBindingElement; 9 | 10 | public MtomMessageEncoderBindingElement(MessageEncodingBindingElement innerEncodingBindingElement) 11 | { 12 | _innerEncodingBindingElement = innerEncodingBindingElement; 13 | } 14 | 15 | public override BindingElement Clone() 16 | { 17 | return new MtomMessageEncoderBindingElement(_innerEncodingBindingElement); 18 | } 19 | 20 | public override MessageEncoderFactory CreateMessageEncoderFactory() 21 | { 22 | return new MtomMessageEncoderFactory(_innerEncodingBindingElement.CreateMessageEncoderFactory()); 23 | } 24 | 25 | public override IChannelFactory BuildChannelFactory(BindingContext context) 26 | { 27 | if (context == null) 28 | throw new ArgumentNullException(nameof(context)); 29 | 30 | context.BindingParameters.Add(this); 31 | 32 | return context.BuildInnerChannelFactory(); 33 | } 34 | 35 | public override bool CanBuildChannelFactory(BindingContext context) 36 | { 37 | return _innerEncodingBindingElement.CanBuildChannelFactory(context); 38 | } 39 | 40 | public override T GetProperty(BindingContext context) 41 | { 42 | return _innerEncodingBindingElement.GetProperty(context); 43 | } 44 | 45 | public override MessageVersion MessageVersion 46 | { 47 | get => _innerEncodingBindingElement.MessageVersion; 48 | set => _innerEncodingBindingElement.MessageVersion = value; 49 | } 50 | } 51 | } -------------------------------------------------------------------------------- /src/WcfCoreMtomEncoder/MtomMessageEncoderFactory.cs: -------------------------------------------------------------------------------- 1 | using System.ServiceModel.Channels; 2 | 3 | namespace WcfCoreMtomEncoder 4 | { 5 | public class MtomMessageEncoderFactory : MessageEncoderFactory 6 | { 7 | private readonly MessageEncoderFactory _innerMessageEncoderFactory; 8 | 9 | public MtomMessageEncoderFactory(MessageEncoderFactory innerMessageEncoderFactory) 10 | { 11 | _innerMessageEncoderFactory = innerMessageEncoderFactory; 12 | } 13 | 14 | public override MessageEncoder CreateSessionEncoder() 15 | { 16 | return new MtomMessageEncoder(_innerMessageEncoderFactory.CreateSessionEncoder()); 17 | } 18 | 19 | public override MessageEncoder Encoder => new MtomMessageEncoder(_innerMessageEncoderFactory.Encoder); 20 | 21 | public override MessageVersion MessageVersion => _innerMessageEncoderFactory.MessageVersion; 22 | } 23 | } -------------------------------------------------------------------------------- /src/WcfCoreMtomEncoder/MtomPart.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.IO; 3 | using System.Linq; 4 | using System.Net.Http; 5 | using System.Net.Http.Headers; 6 | using System.ServiceModel.Channels; 7 | using System.Text; 8 | using System.Text.RegularExpressions; 9 | 10 | namespace WcfCoreMtomEncoder 11 | { 12 | internal class MtomPart 13 | { 14 | private readonly HttpContent _part; 15 | 16 | public MtomPart(HttpContent part) 17 | { 18 | _part = part; 19 | } 20 | 21 | public MediaTypeHeaderValue ContentType 22 | { 23 | get 24 | { 25 | string contentTypeHeaderValue = _part.Headers.GetValues("Content-Type").FirstOrDefault(); 26 | 27 | if (!String.IsNullOrEmpty(contentTypeHeaderValue) && MediaTypeHeaderValue.TryParse(contentTypeHeaderValue.TrimEnd(';'), out var parsedValue)) 28 | return parsedValue; 29 | 30 | return _part.Headers.ContentType; 31 | } 32 | } 33 | 34 | public string ContentTransferEncoding => _part.Headers.TryGetValues("Content-Transfer-Encoding", out var values) ? values.Single() : null; 35 | public string ContentId => _part.Headers.TryGetValues("Content-ID", out var values) ? values.Single() : null; 36 | 37 | public byte[] GetRawContent() 38 | { 39 | if (!Regex.IsMatch(ContentTransferEncoding, "((7|8)bit)|binary", RegexOptions.IgnoreCase)) 40 | throw new NotSupportedException(); 41 | 42 | return ReadFromStream(); 43 | } 44 | 45 | public string GetStringContentForEncoder(MessageEncoder encoder) 46 | { 47 | if (ContentType == null || 48 | !ContentType.Parameters.Any(p => p.Name == "type" && encoder.IsContentTypeSupported(p.Value.Replace("\"", "")))) 49 | { 50 | throw new NotSupportedException(); 51 | } 52 | 53 | var encoding = ContentType.CharSet != null ? Encoding.GetEncoding(ContentType.CharSet) : Encoding.Default; 54 | 55 | return encoding.GetString(GetRawContent()); 56 | } 57 | 58 | private byte[] ReadFromStream() 59 | { 60 | using (var buffer = new MemoryStream()) 61 | { 62 | _part.ReadAsStreamAsync().Result.CopyTo(buffer); 63 | return buffer.ToArray(); 64 | } 65 | } 66 | } 67 | } -------------------------------------------------------------------------------- /src/WcfCoreMtomEncoder/WcfCoreMtomEncoder.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | netstandard2.0 5 | 7.1 6 | MTOM message encoder for .NET Core WCF 7 | Lenny Kean 8 | MIT 9 | https://github.com/lennykean/WcfCoreMtomEncoder 10 | WcfCoreMtomEncoder 11 | True 12 | True 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | --------------------------------------------------------------------------------