.NET 7 Preview 2更新ASP.NET Core——安装引导和新功能代码示例

163 阅读4分钟

.NET 7预览版2现已发布,其中包括ASP.NET Core的许多伟大的新改进。

下面是这个预览版中的新内容摘要。

  • 推断来自服务的API控制器动作参数
  • 为SignalR中心方法进行依赖性注入
  • 为最小的API提供端点描述和摘要
  • 在最小的API中从头文件和查询字符串中绑定数组和StringValues
  • 自定义cookie的同意值

关于为.NET 7计划的ASP.NET Core工作的更多细节,请参见GitHub上完整的.NET 7的ASP.NET Core 路线图

开始使用

要开始使用.NET 7 Preview 2中的ASP.NET Core,请安装.NET 7 SDK

如果你在Windows上使用Visual Studio,我们建议安装最新的Visual Studio 2022预览版。Visual Studio for Mac对.NET 7预览版的支持尚不可用,但即将推出。

要安装最新的.NET WebAssembly构建工具,请在高位命令提示符下运行以下命令:

dotnet workload install wasm-tools

升级一个现有的项目

要将现有的ASP.NET Core应用程序从.NET 7 Preview 1升级到.NET 7 Preview 2:

  • 将所有Microsoft.AspNetCore.*包的引用更新为7.0.0-preview.2.*
  • 将所有Microsoft.Extensions.*包的引用更新到7.0.0-preview.2.*

另请参见ASP.NET Core for .NET 7中的全部中断变化列表。

推断来自服务的API控制器动作参数

当类型被配置为服务时,API控制器动作的参数绑定现在通过依赖性注入来绑定参数。这意味着不再需要明确地将[FromServices] 属性应用于参数:

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();
}

你可以通过设置DisableImplicitFromServicesParameters 来禁用该功能:

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

SignalR hub方法的依赖注入

SignalR hub方法现在支持通过依赖注入(DI)来注入服务:

Services.AddScoped<SomeCustomType>();

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

你可以通过设置DisableImplicitFromServicesParameters 来禁用该功能:

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

要明确地标记一个参数,从配置的服务中绑定,使用[FromServices] 属性:

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

为最小的API提供端点描述和摘要

最小的API现在支持用用于生成OpenAPI规范的描述和摘要来注释操作。你可以在你的最小API应用程序中使用扩展方法为路由处理程序设置这些描述和摘要:

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

或者通过路由处理委托的属性来设置描述或摘要:

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

在最小的API中从头文件和查询字符串中绑定数组和StringValues

在这个版本中,你现在可以将HTTPS头信息和查询字符串的值绑定到原始类型的数组、字符串数组或StringValues

// Bind query string values to a primitive type array
// GET  /tags?q=1&q=2&q=3
app.MapGet("/tags", (int[] q) => $"tag1: {q[0]} , tag2: {q[1]}, tag3: {q[2]}")

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

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

你也可以将查询字符串或头信息的值绑定到一个复杂类型的数组中,只要该类型有TryParse 实现,如下例所示:

// Bind to an array of a complex type
// GET /tags?tags=trendy&tags=hot&tags=spicy
app.MapGet("/tags", (Tag[] tags) =>
{
    return Results.Ok(tags);
});

...

class Tag 
{
    public string? TagName { get; init; }

    public static bool TryParse(string? tagName, out Tag tag)
    {
        if (tagName is null) 
        {
            tag = default;
            return false;
        }

        tag = new Tag { TagName = tagName };
        return true;
    }
}

自定义cookie的同意值

你现在可以使用新的CookiePolicyOptions.ConsentCookieValue 属性来指定用于跟踪用户是否同意cookie使用政策的值。

请求对IIS的卷影复制进行反馈

在.NET 6中,我们为IIS的ASP.NET核心模块(ANCM)增加了对影子复制应用程序集的试验性支持。当ASP.NET Core应用程序在Windows上运行时,二进制文件被锁定,因此它们不能被修改或替换。你可以通过部署一个应用程序离线文件来停止该应用程序,但有时这样做是不方便的或不可能的。卷影复制使应用程序集可以在应用运行时通过制作程序集的副本来更新。

你可以通过自定义web.config中的ANCM处理程序设置来启用卷影复制:

<?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>

我们正在研究将IIS中的影子复制作为.NET 7中ASP.NET Core的一项功能,我们正在寻求关于该功能是否满足用户需求的额外反馈。如果你将ASP.NET Core部署到IIS,请尝试一下影子复制,并在GitHub上与我们分享你的反馈

提供反馈

我们希望你喜欢这个.NET 7中的ASP.NET Core预览版。通过在GitHub上提交问题,让我们知道你对这些新的改进有什么看法。

感谢你尝试使用ASP.NET Core!