最好的新特性在ASP。网络核心7

微软最新版本的web应用程序开发框架带来优秀的新功能中间件,最小的API的应用程序等等。这是亮点。

  • 在Facebook上分享
  • 在Twitter上分享
  • 分享在LinkedIn
  • 在Reddit分享
  • 通过电子邮件分享
  • 印刷资源
在上面2168992649
帕特里克Krabeepetcharat /伤风

的一个重要部分微软的。net 7发布“云”去年11月,ASP。网络核心7brings powerful new tools to the web development framework to help developers create modern web applications. Built on top of the .NET Core runtime, ASP.NET Core 7 has everything you need to build cutting-edge web user interfaces and robust back-end services on Windows, Linux, and macOS alike.

本文讨论了ASP的最大亮点。网络核心7,and includes some code examples to get you started with the new features. To work with the code examples provided in this article, you should have Visual Studio 2022 installed in your computer. If you don’t have a copy, you can在这里下载Visual Studio 2022

现在让我们深入最好的新特性在ASP。网络核心7。

输出缓存的中间件

ASP。网络核心7允许您使用输出缓存所有ASP。网络核心apps: Minimal API, MVC, Razor Pages, and Web API apps with controllers. To add the output caching middleware to the services collection, invoke the IServiceCollection.AddOutputCache extension method. To add the middleware to the request processing pipeline, call the IApplicationBuilder.UseOutputCache extension method.

然后,添加一个缓存层端点,您可以使用下面的代码。

var builder = WebApplication.CreateBuilder (args);应用var = builder.Build ();app.MapGet (“/”, () = >“Hello World !”) .CacheOutput ();app.Run ();

病原的中间件

控制客户可以请求的端点是一个重要的安全措施,允许web应用程序来抵御恶意攻击。你可以阻止拒绝服务攻击,例如,通过限制来自一个单一的IP地址的请求数量在一个给定的一段时间。此功能的术语是率限制。

Microsoft.AspNetCore。RateLimiting中间件在ASP。网络核心7can help you enforce rate limiting in your application. You can configure rate-limiting policies and then attach those policies to the endpoints, thereby protecting those endpoints from denial-of-service attacks. This middleware is particularly useful for public-facing web applications that are susceptible to such attacks.

您可以使用病原中间件与ASP。网络核心Web API, ASP。网络核心MVC, ASP。网络核心Minimal API apps. To get started using this built-in middleware, add the Microsoft.AspNetCore.RateLimiting NuGet package to your project by executing the following command at the Visual Studio command prompt.

dotnet添加包Microsoft.AspNetCore.RateLimiting

或者,您可以将这个包添加到您的项目通过运行以下命令在NuGet包管理器控制台或控制台窗口:

安装包Microsoft.AspNetCore.RateLimiting

一旦病原中间件已经安装,包括程序下面的代码片段。cs文件添加率限制服务使用默认配置。

builder.Services。AddRateLimiter(选项= > {});

请求减压中间件

ASP。网络核心7包含了一个新的请求减压中间件,允许端点接受请求压缩的内容。这消除了需要编写代码显式减压与压缩内容请求。它通过使用HTTP报头内容编码识别和解压压缩内容在HTTP请求。

在回应一个HTTP请求匹配内容编码头值,HttpRequest的中间件封装。身体在一个适当的减压流使用匹配的供应商。这是紧随其后的内容编码头,这表明请求主体不再是压缩。注意,请求减压中间件忽略请求内容编码标头。

下面的代码片段显示了如何启用请求减压为默认内容编码类型。

var builder = WebApplication.CreateBuilder (args);builder.Services.AddRequestDecompression ();应用var = builder.Build ();app.UseRequestDecompression ();app.MapPost (“/”(HttpRequest HttpRequest) = > Results.Stream (httpRequest.Body));app.Run ();

默认的减压提供者Brotli,缩小,Gzip压缩格式。他们的内容编码标头值br、缩小和gzip,分别。

过滤器在最小的api

过滤器允许您执行代码在某些阶段在请求处理管道。一个过滤器运行之前或之后执行一个动作方法。您可以利用过滤器来跟踪网页访问或验证请求参数。通过使用过滤器,您可以专注于应用程序的业务逻辑,而不是编写代码为您的应用程序的横切关注点。

端点过滤器使您能够截获、修改短路,和总横切问题,如授权、验证和异常处理。新的IEndpointFilter界面在ASP。网络核心7lets us design filters and connect them to API endpoints. These filters may change request or response objects or short-circuit request processing. An endpoint filter can be invoked on actions and on route endpoints.

Microsoft.AspNetCore IEndpointFilter接口定义。Http命名空间如下所示。

公共接口IEndpointFilter {ValueTask <对象?> InvokeAsync (EndpointFilterInvocationContext上下文,EndpointFilterDelegate下);}

下面的代码片段说明了多个端点过滤器可以链接在一起的。

app.MapGet(“/”,() = >{返回“展示多个端点过滤器。”;}).AddEndpointFilter(异步(endpointFilterInvocationContext,) = > {app.Logger。LogInformation(“这是第一过滤器。”);var =等待下一个结果(endpointFilterInvocationContext);返回结果;}).AddEndpointFilter(异步(endpointFilterInvocationContext,) = > {app.Logger。LogInformation(“这是第二过滤器。”);var =等待下一个结果(endpointFilterInvocationContext);返回结果;}).AddEndpointFilter(异步(endpointFilterInvocationContext,) = > {app.Logger。LogInformation(“这是第三滤波器。”);var =等待下一个结果(endpointFilterInvocationContext);返回结果; });

参数绑定在行动中使用依赖注入的方法

ASP。网络核心7, you can take advantage of dependency injection to bind parameters in the action methods of your API controllers. So, if the type is configured as a service, you no longer need to add the [FromServices] attribute to your method parameters. The following code snippet illustrates this.

[路线(“(控制器)”)][ApiController]公开课MyDemoController: ControllerBase{公共ActionResult (IDateTime dateTime) = > Ok (dateTime.Now);}

输入导致最小的api

IResult界面增加了在。net 6代表返回值最小的api,不利用隐式支持JSON序列化对象返回。这里应该注意,静态结果类用于创建各种IResult对象代表不同类型的反应,如设置返回状态代码或者用户重路由到一个新的URL。然而,由于这些方法返回的框架类型是私人的,无法验证正确的IResult在单元测试期间从操作方法返回类型。

在。net 7,框架类型实现IResult接口现在公众。因此我们可以使用类型的断言在编写单元测试,如下面代码片段所示。

[TestClass()]公共类MyDemoApiTests {(TestMethod())公共空MapMyDemoApiTest () {var =结果_MyDemoApi.GetAllData ();断言。IsInstanceOfType(因此,typeof(好< MyDemoModel [] >));}}

您还可以使用IResult实现类型单元测试你的路由处理程序最少的api。下面的代码片段说明了这一点。

var结果=(好< MyModel >)等待_MyDemoApi.GetAllData ()

最小的路线团体api

ASP。网络核心7, you can leverage the new MapGroup extension method to organize groups of endpoints that share a common prefix in your minimal APIs. The MapGroup extension method not only reduces repetitive code, but also makes it easier to customize entire groups of endpoints.

下面的代码片段显示了如何使用MapGroup。

app.MapGroup(“/公共/作者”).MapAuthorsApi () .WithTags(“公共”);

在下一个代码片段说明了MapAuthorsApi扩展方法。

公共静态类MyRouteBuilder{公共静态RouteGroupBuilder MapAuthorsApi(这RouteGroupBuilder集团){组。GetAllAuthors MapGet (“/”);组。MapGet (“/ {id}”, GetAuthor);组。CreateAuthor MapPost (“/”);组。MapPut (“/ {id}”, UpdateAuthor);组。MapDelete (“/ {id}”, DeleteAuthor);返回组; } }

健康检查gRPC

ASP。网的核心支持使用. NET健康检查中间件应用程序基础设施组件的健康报告。ASP。净核心7增加了内置支持监控的健康通过Grpc.AspNetCore gRPC服务。healthcheck NuGet包。你可以用这个包来揭露一个端点在你gRPC应用,使健康检查。

注意,您通常使用与外部监控系统健康检查,协调器与负载均衡器或容器。后者可能自动化操作,如重启或重路由的服务基于健康状态。你可以阅读更多关于ASP。网络核心健康检查在这里

文件上传在最小的api

您现在可以使用IFormFile和IFormFileCollection最小api在ASP上传文件。网络核心7。下面的代码片段说明了如何使用IFormFile。

var builder = WebApplication.CreateBuilder (args);应用var = builder.Build ();app.MapPost(“还是”,异步(IFormFile IFormFile) = > {var tempFileName = Path.GetTempFileName ();使用var = fileStream File.OpenWrite (tempFileName);等待iformFile.CopyToAsync(文件流);});app.Run ();

如果你想上传多个文件,您可以使用以下的代码来代替。

var builder = WebApplication.CreateBuilder (args);应用var = builder.Build ();app.MapPost(“/”还是异步(IFormFileCollection文件)= > {foreach (var文件文件){var tempFileName = Path.GetTempFileName ();使用var = fileStream File.OpenWrite (tempFileName);等待file.CopyToAsync(文件流);}});app.Run ();

从输出缓存、病原和请求减压中间件过滤器,路线地图,和其他新功能最小的api, ASP。净核心7给开发商许多新特性,会让你更容易和更快的创建健壮的web应用程序。ASP。网络核心7允许更快的开发使用模块化的组件,提供了更好的性能和可伸缩性跨多个平台,并简化了部署到web主机,码头工人,Azure和其他承载环境内置工具。

在本文中我们讨论了在ASP只有一些重要的新特性。核心网我的首选。你可以找到新特性的完整列表在ASP。网络核心7在这里

版权©2023 IDG通信公司。

奖2023年信息世界的技术。现在打开条目!