Missing compiler required member ‚Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create‘

You are working in a .net Core or .net Standard codebase and get the error „Missing compiler required member ‚Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create“. In my case it appears when I used the dynamic type. The solution is to load the nuget package Microsoft.CSharp. After you installed it and write a using to your code everything should work as expected.

Error 405 – Methods not allowed in Asp.Net Core application

I developed an Api in Asp.Net Core Web Api. While testing it on my local machine verything works fine. When I deployed it to my Ionos Managed Windows Hosting I got a 405 Http Error on some Endpoints. Analyzing this behaviour showed me that only controller methods with PUT and DELETE annotations throwed the error.

The problem seems to be the WebDav Module of IIS blocking PUT and DELETE requests by default.

Solution: Remove WebDav in the web.config file.


<system.webServer>
<handlers>
<remove name="WebDAV" />
<add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModuleV2" resourceType="Unspecified" />
</handlers>
<modules>
<remove name="WebDAVModule" />
</modules>
</system.webServer>

Using Refit with Factory and Proxy

Sometimes a webhost wants you to use a proxy to communicate via http with an API for example. If you use Refit in C# with Factory implementation you can use the following code:


services.AddRefitClient()
.ConfigureHttpClient(c => c.BaseAddress = new Uri(Configuration.GetValue("The name of the value in your appsettings.json")))
.ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler()
{
UseProxy = true,
Proxy = new WebProxy("http://yourProxyUrl:yourProxyPort", false),
PreAuthenticate = true,
UseDefaultCredentials = false
});

Set multiple startup projects in Visual Studio

There are use-cases where you want to start multiple projects of your solution at once in Visual Studio. For example if you’re developing a website in Asp.Net Core MVC getting it’s data of an Asp.Net Core Web API application. You’ll have to do the following steps to set multiple startup projects:

1) Right click on the top node of your solution in the solution explorer.
2) In the context menu choose Properties (Alt + Enter).
3) Expand the „Common Properties“ node, and choose Startup Project.
4) Select the Multiple Startup Projects radio button option and set the appropriate actions.

The way with less clicks is to click on the little arrow on the left side of the start button and choose Define Start Projects or right click on the solution node and choose Define Start Projects.

Automapper returns empty Collection after mapping

Some days ago I had a problem while mapping domain objects to DTO by automapper. My environment was an Asp.Net Core 3 Web Api project. I created an own profiles class where I stored my mapping logic. In the startup class I registered the mapper service. When running project my source of type List<Product> should be mapped to List<ProductDTO>. But the API always returned an empty list even if the source was filled correctly.

Profile:


CreateMap<Product, ProductDTO>();

CreateMap<List<Product>, List<ProductDTO>>();

The mistake was the second line in my profile class. Automapper automatically maps collections you don’t have to create a map for this case.

Detecting your installed .net core version by console

If want to check which .net core version, sdk’s and runtimes are installed on your machine you can easily check in console by typing:

dotnet --info

You will get a result looking like:

Getting .net core infos in console
Getting .net core infos in console

Like mentioned in the result you can install another version or sdk by visiting https://aka.ms/dotnet-download and following the instructions or do it directly in visual studio.

There you have to open the project properties and select the targetframework dropdown. You can find an option named install another framework there. By clicking on it the browser opens and you’ll be transfered to https://dotnet.microsoft.com/download/visual-studio-sdks where you can download runtimes and sdk’s.

Injecting scoped service in a singleton service

If you want to use a scoped service in a singleton service in a Asp.Net Core MVC project you can’t inject it via constructor injection. You’ll have to create a scope when needed. In my case I needed to use a DbContext service regisered with .AddDbContext as a scoped service in startup.cs into a hosted service.

First you have to create a service inheriting of IHostedService (Microsoft.Extensions.Hosting) with the following code:


public abstract class HostedService : IHostedService
{
// Example untested base class code kindly provided by David Fowler: https://gist.github.com/davidfowl/a7dd5064d9dcf35b6eae1a7953d615e3

private Task _executingTask;
private CancellationTokenSource _cts;

public Task StartAsync(CancellationToken cancellationToken)
{
// Create a linked token so we can trigger cancellation outside of this token's cancellation
_cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);

// Store the task we're executing
_executingTask = ExecuteAsync(_cts.Token);

// If the task is completed then return it, otherwise it's running
return _executingTask.IsCompleted ? _executingTask : Task.CompletedTask;
}

public async Task StopAsync(CancellationToken cancellationToken)
{
// Stop called without start
if (_executingTask == null)
{
return;
}

// Signal cancellation to the executing method
_cts.Cancel();

// Wait until the task completes or the stop token triggers
await Task.WhenAny(_executingTask, Task.Delay(-1, cancellationToken));

// Throw if cancellation triggered
cancellationToken.ThrowIfCancellationRequested();
}

// Derived classes should override this and execute a long running method until
// cancellation is requested
protected abstract Task ExecuteAsync(CancellationToken cancellationToken);
}

The following code in the singleton service works for me:

public class AnyService
{
    private readonly IServiceScopeFactory _scopeFactory;

    public AnyService(IServiceScopeFactory scopeFactory)
    {
        _scopeFactory = scopeFactory;
    }

    public void Execute()
    {
        using (var scope = _scopeFactory.CreateScope())
        {
            var dbContext = scope.ServiceProvider.GetRequiredService<MyDbContext>();
            
        }
    }
    
}