.NET 7: Microsoft Reveals New ASP.NET Core Features
Tags: csharp, dotnet, news, beginners
Published: 2022-08-29 11:50:53

Microsoft has revealed more new features that will be included in its next version of ASP.NET Core for .NET 7. This new preview includes API enhancements, cookie consent customization, support for shadow copying and more. Let’s take a look at what’s new in ASP.NET Core in .NET 7!

## Infer service-sourced API controller action parameters

Previously it was necessary to apply the `[FromServices]` attribute to the parameters. Now thanks to this update, parameter binding for **API controller** **actions** has the ability to [**bind them via dependency injections**](https://devblogs.microsoft.com/dotnet/asp-net-core-updates-in-dotnet-7-preview-2/#infer-api-controller-action-parameters-that-come-from-services).

Let’s look at the [Microsoft example](https://devblogs.microsoft.com/dotnet/asp-net-core-updates-in-dotnet-7-preview-2/#infer-api-controller-action-parameters-that-come-from-services):

```csharp
Services.AddScoped<SomeCustomType>();

[Route("[controller]")]
[ApiController]
public class MyController : ControllerBase
{
    // Both actions will bound the SomeCustomType from the DI container
    public ActionResult GetWithAttribute([FromServices]SomeCustomType service) => Ok();
    public ActionResult Get(SomeCustomType service) => Ok();
}
```

But this is not mandatory. Apart from being able to link the parameters by injecting them, we can also simply disable it in case we do not want to use it. In order to disable this we simply need to use [DisableImplicitFromServicesParameters](https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.apibehavioroptions.disableimplicitfromservicesparameters?view=aspnetcore-7.0).

Let’s look again at the [example provided by Microsoft](https://devblogs.microsoft.com/dotnet/asp-net-core-updates-in-dotnet-7-preview-2/#infer-api-controller-action-parameters-that-come-from-services):

```csharp
Services.Configure<ApiBehaviorOptions>(options =>
{
     options.DisableImplicitFromServicesParameters = true;
})
```

If you want to know more about this feature, I recommend you, as always, to consult the original source: [Infer API controller action parameters that come from services](https://devblogs.microsoft.com/dotnet/asp-net-core-updates-in-dotnet-7-preview-2/#infer-api-controller-action-parameters-that-come-from-services)

## Dependency injection for SignalR hub methods

If you remember ASP.NET Core Preview 1 in .NET 7, you will recall that SignalR enhancements were added. In the last Preview a new client source generator for SignalR was added.

Now, in this preview, using **Dependency Injection** (DI) we have the possibility to [**inject services with the SignalR hub methods**](https://devblogs.microsoft.com/dotnet/asp-net-core-updates-in-dotnet-7-preview-2/#dependency-injection-for-signalr-hub-methods) (_thanks Microsoft for adding this support_):

```csharp
Services.AddScoped<SomeCustomType>();

public class MyHub : Hub
{
    // SomeCustomType comes from DI by default now
    public Task Method(string text, SomeCustomType type) => Task.CompletedTask;
}
```

In addition, we can [explicitly mark only one parameter](https://devblogs.microsoft.com/dotnet/asp-net-core-updates-in-dotnet-7-preview-2/#dependency-injection-for-signalr-hub-methods). This is useful to be able to link only that parameter from the configured services. To do this, simply configure the `[FromServices]` attribute:

```csharp
public class MyHub : Hub
{
    public Task Method(string arguments, [FromServices] SomeCustomType type);
}
```

And of course, we also have the possibility to disable this dependency injection. To do this, again [following Microsoft’s example](https://devblogs.microsoft.com/dotnet/asp-net-core-updates-in-dotnet-7-preview-2/#dependency-injection-for-signalr-hub-methods), we must configure `DisableImplicitFromServicesParameters`:

```csharp
services.AddSignalR(options =>
{
    options.DisableImplicitFromServicesParameters = true;
});
```

If you want to know more about this feature, I recommend you, as always, to consult the original source: [Dependency injection for SignalR hub methods](https://devblogs.microsoft.com/dotnet/asp-net-core-updates-in-dotnet-7-preview-2/#dependency-injection-for-signalr-hub-methods)

## Minimal API endpoint summaries and descriptions

As a new feature in this Preview, it is now possible to [**set summaries and descriptions for route handlers**](https://devblogs.microsoft.com/dotnet/asp-net-core-updates-in-dotnet-7-preview-2/#provide-endpoint-descriptions-and-summaries-for-minimal-apis). This feature is because Microsoft has added support for annotations, descriptions and operation summaries in the minimal APIs. This is mainly used for **generating OpenAPI specifications**.

Let’s see [how Microsoft applies it in its example](https://devblogs.microsoft.com/dotnet/asp-net-core-updates-in-dotnet-7-preview-2/#provide-endpoint-descriptions-and-summaries-for-minimal-apis) with extension methods:

```csharp
app.MapGet("/hello", () => ...)
  .WithDescription("Sends a request to the backend HelloService to process a greeting request.");
```

Another thing we can do is to **use an attribute on the route handler delegate to set a summary or description**. According to the example:

```csharp
app.MapGet("/hello", [EndpointSummary("Sends a Hello request to the backend")]() => ...)
```

If you want to know more about this feature, I recommend you, as always, to consult the original source: [Provide endpoint descriptions and summaries for minimal APIs](https://devblogs.microsoft.com/dotnet/asp-net-core-updates-in-dotnet-7-preview-2/#provide-endpoint-descriptions-and-summaries-for-minimal-apis)

## Bind HTTPS header and query string values to arrays

This is the next feature presented in this second preview by Microsoft. What this feature allows us is the ability to bind query strings and HTTPS header values to `StringValues` or any primitive type array.

For example if we want to bind to a string array:

```csharp
// GET /tags?names=john&names=jack&names=jane
app.MapGet("/tags", (string[] names) => $"tag1: {names[0]} , tag2: {names[1]}, tag3: {names[2]}")
```

To bind query string values to a primitive type array:

```csharp
// GET  /tags?q=1&q=2&q=3
app.MapGet("/tags", (int[] q) => $"tag1: {q[0]} , tag2: {q[1]}, tag3: {q[2]}")
```

And to bind to `StringValues` :

```csharp
// GET /tags?names=john&names=jack&names=jane
app.MapGet("/tags", (StringValues names) => $"tag1: {names[0]} , tag2: {names[1]}, tag3: {names[2]}")
```

You can check these examples here: [Binding arrays and StringValues from headers and query strings in minimal APIs](https://devblogs.microsoft.com/dotnet/asp-net-core-updates-in-dotnet-7-preview-2/#binding-arrays-and-stringvalues-from-headers-and-query-strings-in-minimal-apis)

## Cookie consent value customization

This feature was contributed by [David De Smet](https://github.com/daviddesmet). This feature allows to use the property `CookiePolicyOptions.ConsentCookieValue` to **add a custom value for tracking** (_only if the user or visitor accepts the cookie policy_).

In [Dotnet’s Github they provide this example](https://github.com/dotnet/aspnetcore/issues/40164):

```csharp
services.Configure<CookiePolicyOptions>(options =>
{
    options.CheckConsentNeeded = context => true;
    options.ConsentCookieValue = "true";
});
```

There is little more information about this feature. If you want to know more about it I recommend you to [check this feature in Github](https://github.com/dotnet/AspNetCore.Docs/issues/26341)

## Shadow copying for IIS request

Shadow copying allows you to update the different assemblies of an application while it is running. When an ASP.NET Core application is running on Windows, these binaries are blocked to prevent any modification. Obviously it is possible to stop the app by deploying a copy of the file offline, but in most cases this is not ideal. For this, this shadow copying feature can **make a copy of the assemblies so that it can be updated**.

In order to enable this feature, [according to Microsoft](https://devblogs.microsoft.com/dotnet/asp-net-core-updates-in-dotnet-7-preview-2/#request-for-feedback-on-shadow-copying-for-iis), you simply need to modify the **ANCM handler** settings in the `web.config` file:

```xml
<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <system.webServer>
    <handlers>
      <remove name="aspNetCore"/>
      <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModuleV2" resourceType="Unspecified"/>
    </handlers>
    <aspNetCore processPath="%LAUNCHER_PATH%" arguments="%LAUNCHER_ARGS%" stdoutLogEnabled="false" stdoutLogFile=".logsstdout">
      <handlerSettings>
        <handlerSetting name="experimentalEnableShadowCopy" value="true" />
        <handlerSetting name="shadowCopyDirectory" value="../ShadowCopyDirectory/" />
      </handlerSettings>
    </aspNetCore>
  </system.webServer>
</configuration>
```

Microsoft also adds:

> “We’re investigating making shadow copying in IIS a feature of ASP.NET Core in .NET 7, and we’re seeking additional feedback on whether the feature satisfies user requirements.”

If you want to know more about this feature, I recommend you, as always, to consult the original source: [Request for feedback on shadow copying for IIS](https://devblogs.microsoft.com/dotnet/asp-net-core-updates-in-dotnet-7-preview-2/#request-for-feedback-on-shadow-copying-for-iis)

At this time, we continue to keep our fingers crossed that Microsoft will release some fresh details soon. What new things does Microsoft have in mind for us over the next several weeks or months? What will take us by surprise? Microsoft is the only one who knows.