WCF in .NET core

.NET

Here are some simple steps to setup a working web service using the CoreWCF libray in a .NET core project

Step 1 - Add dependencies

  • Nuget CoreWCF.Http
  • Nuget CoreWCF.Primitives

Step 2 - Add contract and implementation


[ServiceContract]
public interface IMyService
{
    [OperationContract]
    Task<bool> IsAlive();
}

public class MyService : IMyService
{
    public async Task<bool> IsAlive() 
    {
    	return true;
    }
}

Step 3 - Add to startup


builder.Services.AddServiceModelServices()
        .AddServiceModelMetadata();
builder.Services.AddSingleton<IServiceBehavior, UseRequestHeadersForMetadataAddressBehavior>();

builder.Services.AddTransient<MyService>();

...

app.UseServiceModel(builder =>
{
    BasicHttpBinding binding = new(BasicHttpSecurityMode.Transport)
    {
        MaxBufferSize = int.MaxValue,
        MaxReceivedMessageSize = int.MaxValue
    };
    binding.ReaderQuotas.MaxArrayLength = int.MaxValue;
    binding.ReaderQuotas.MaxDepth = int.MaxValue;
    binding.ReaderQuotas.MaxBytesPerRead = int.MaxValue;
    binding.ReaderQuotas.MaxNameTableCharCount = int.MaxValue;
    binding.ReaderQuotas.MaxStringContentLength = int.MaxValue;

    builder.AddService<MyService>((serviceOptions) =>
    {
        serviceOptions.DebugBehavior.IncludeExceptionDetailInFaults = true;
    })
    .AddServiceEndpoint<MyService, IMyService>(binding, "MyService.svc/soap");

});

var serviceMetadataBehavior = app.Services.GetRequiredService<ServiceMetadataBehavior>();
serviceMetadataBehavior.HttpGetEnabled = true;
serviceMetadataBehavior.HttpsGetEnabled= true;
serviceMetadataBehavior.HttpGetUrl = new Uri("MyService.svc", UriKind.Relative);
serviceMetadataBehavior.HttpsGetUrl = new Uri("MyService.svc", UriKind.Relative);

Post a Comment

Previous Post Next Post