Translate. ASP in NET 7 Preview Version 1. NET Core Update

Posted by sahammondsr on Tue, 08 Mar 2022 18:12:41 +0100

Python WeChat Subscription Applet Course Video

https://edu.csdn.net/course/detail/36074

Python Actual Quantitative Transaction Finance System

https://edu.csdn.net/course/detail/35475
Original | Daniel Roth

Translation|Zheng Ziming

Preview version 1 of.NET 7 is now available! This is. The first preview of the next major version of NET, which will include the use of ASP.NET Core is the next wave of innovation for Web development.

In. NET 7, we plan on ASP.NET Core invests extensively. Here are some areas that we plan to focus on:

  • Performance:. NET 6 Contains For ASP. Many performance improvements for NET Core We will work hard to make ASP.NET Core in. NET 7 is faster and more efficient.
  • HTTP/3: HTTP/3 support as. The preview function in NET 6 is available. For. NET 7, which we want to complete and make supported by default. In future previews, you can expect to see advanced TLS functionality and more performance improvements in our HTTP/3 support.
  • Minimum API: Adds support for endpoint filters and routing grouping as the core primitive of the minimum API. Authentication and authorization configurations for APIs are also typically simplified.
  • GRPC: We are investing in gRPC JSON transcoding. This feature allows the gRPC service to be called like the RESTful HTTP API with JSON requests and responses.
  • SignalR: Add support for strongly typed clients and return results from client calls.
  • Razor: We will make various improvements to the Razor compiler to improve performance, resilience, and tools for improvement.
  • Blazor: Finishing pairing. With Blazor Hybrid support for NET MAUI, WPF, and Windows forms, we will make extensive improvements to Blazor, including:
    • New. NET Web Assembly features: mixed mode AOT, multithreading, Web encryption.
    • Enhanced hot overload support.
    • Data binding improvements.
    • More flexible pre-rendering.
    • Better control over the life cycle of Blazor server circuits.
    • Improved support for micro front end.
  • MVC: Improvements to endpoint routing, link generation, and parameter binding.
  • Orleans:ASP. The NET Core and Orleans teams are investigating further adjustments and integration of the Orleans distributed programming model with ASP.NET Core method. Orleans 4 will join. NET 7 was released with a focus on simplicity, maintainability, and performance, including human-readable stream identities and new optimized, version-tolerant serializers.

About. NET 7 Program Specific ASP. For more details on how NET Core works, see GitHub In the light of. Complete ASP for NET 7. NET Core Roadmap.

.NET 7 Preview 1 is numerous. NET 7 preview version of the first, November 222. NET Version 7 Ready.

I am here Last episode On. NET Joined in James Montemagno To decompose. NET 7 and. ASP in NET 7. All in NET Core:

Here is a summary of what's new in this preview:

  • Minimum API improvements:
    • IFormFile and IFormFileCollection support
    • Bind request body to Stream or PipeReader
    • JSON Options Configuration
  • SignalR Client Source Generator
  • Supports nullable models in MVC views and Razor pages
  • Use JSON property name in validation errors
  • Improved console output for dotnet watch
  • Configure dotnet watch to always restart for rude editing
  • Using Dependent Injection in ValidationAttribute
  • Faster header parsing and writing
  • gRPC JSON Transcoding

Start using

To get started. ASP in NET 7 Preview 1. NET Core, please Installation. NET 7 SDK.

If you use Visual Studio on Windows, we recommend installing the latest Visual Studio 2022 Preview . Visual Studio for Mac pairs. Support for NET 7 preview is not yet available but will be available soon.

To install the latest. NET Web Assembly Builder, run the following command from an elevated command prompt:

dotnet workload install wasm-tools

Upgrade existing projects

To add an existing ASP.NET Core application from. NET 6 upgrade to. NET 7 Preview 1:

  • Update the target framework of your application to net7.0.
  • All Microsoft.AspNetCore. * Package reference updated to 7.0.0-preview.1. *.
  • All Microsoft.Extensions. * Package reference updated to 7.0.0-preview.1. *.

See also. ASP for NET 7. In NET Core Major changes Complete list.

Minimum API improvements

IFormFile and IFormFileCollection support

You can now use IFormFile and IFormFileCollection to handle file uploads in the minimum API:

app.MapPost("/upload", async(IFormFile file) =>
{
    using var stream = System.IO.File.OpenWrite("upload.txt");
    await file.CopyToAsync(stream); 
});

app.MapPost("/upload", async (IFormFileCollection myFiles) => { ... });

Anti-forgery support is required to use this feature with authentication, but it is not yet implemented. Ours. NET 7 roadmap contains Anti-counterfeiting support for minimum API . Binding to IFormFile or IFormFileCollection is currently disabled when a request contains an Authorization header, client certificate, or cookie header. We will resolve this restriction immediately after completing anti-forgery support.

Thank you @martincostello for contributing this feature.

Bind request body to Stream or PipeReader

You can now bind the request body to Stream or PipeReader to effectively support scene workers or cloud functionality where users must ingest and store data in blob storage or queue data to queue providers (Azure queues, etc.) for later processing. The following example shows how to use the new binding:

app.MapPost("v1/feeds", async (QueueClient queueClient, Stream body, CancellationToken cancellationToken) =>
{
    await queueClient.CreateIfNotExistsAsync(cancellationToken: cancellationToken);
    await queueClient.SendMessageAsync(await BinaryData.FromStreamAsync(body), cancellationToken: cancellationToken);
});

When using Stream or PipeReader, the following points need to be considered:

  • Stream will be associated with HttpRequest when ingesting data. Body is the same object.
  • Request body is not buffered by default. After reading the body, it cannot be fallback (you cannot read the stream multiple times).
  • Stream/PipeReader is not available outside the minimum action handler because the underlying buffer will be released and/or reused.

JSON Options Configuration

We are introducing a new, more concise API, ConfigureRouteHandlerJsonOptions, to configure JSON options for the smallest API endpoints. This new API avoids working with Microsoft. AspNetCore. Mvc. Confusion with JsonOptions.

var builder = WebApplication.CreateBuilder(args);
builder.Services.ConfigureRouteHandlerJsonOptions(options =>
{
    //Ignore Cycles
    options.SerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles; 
});   

SignalR Client Source Generator

Thanks to the contribution of @mehmetakbulut, we have added a new client source generator for SignalR.

The SignalR client source generator generates strongly typed send and receive code based on the interface you define. You can reuse from Strong Type SignalR Hub Replace loose type with same interface. On("methodName",...) method. Similarly, your hub can implement an interface for its method, and clients can use that same interface to invoke the hub method.

To use the SignalR client source generator:

[AttributeUsage(AttributeTargets.Method)]
internal class HubServerProxyAttribute : Attribute
{
}

[AttributeUsage(AttributeTargets.Method)]
internal class HubClientProxyAttribute : Attribute
{
}

  • Add a static partial class to your project and write a static partial method using [HubClientProxy] and [HubServerProxy] attributes
internal static partial class MyCustomExtensions
{
    [HubClientProxy]
    public static partial IDisposable ClientRegistration<T>(this HubConnection connection, T provider);

    [HubServerProxy]
    public static partial T ServerProxy<T>(this HubConnection connection);
}

  • Use some of the methods in the code!
public interface IServerHub
{
    Task SendMessage(string message);
    Task<int> Echo(int i);
}

public interface IClient
{
    Task ReceiveMessage(string message);
}

public class Client : IClient
{
    // Equivalent to HubConnection.On("ReceiveMessage", (message) => {});
    Task ReceiveMessage(string message)
    {
        return Task.CompletedTask;
    }
}

HubConnection connection = new HubConnectionBuilder().WithUrl("...").Build();
var stronglyTypedConnection = connection.ServerProxy();
var registrations = connection.ClientRegistration(new Client());

await stronglyTypedConnection.SendMessage("Hello world");
var echo = await stronglyTypedConnection.Echo(10);

Supports nullable models in MVC views and Razor pages

We have enabled the definition of a nullable page or view model to improve on ASP. Experience with empty state checking in NET Core applications:

@model Product?

Use JSON property name in validation errors

When model validation generates ModelErrorDictionary, by default it uses the property name as the error key ("MyClass.PropertyName"). Model property names are often an implementation detail that makes them difficult to handle from a single-page application. You can now configure validation to use the appropriate JSON property name instead of the new SystemTextJsonValidationMetadataProvider (or Newtonsoft JsonValidationMetadataProvider when using Json.NET).

services.AddControllers(options =>
{
    options.ModelMetadataDetailsProviders.Add(new SystemTextJsonValidationMetadataProvider())
});

Improved console output for dotnet watch

We cleaned up the console output of dotnet watch to better match ASP.NET Core logoff is consistent and 😮 Emoticon 😍. Stand out from the crowd.

The following is an example of the new output:

C:BlazorApp> dotnet watch
dotnet watch 🔥 Hot reload enabled. For a list of supported edits, see https://aka.ms/dotnet/hot-reload.
  💡 Press "Ctrl + R" to restart.
dotnet watch 🔧 Building...
  Determining projects to restore...
  All projects are up-to-date for restore.
 You are using a preview version of .NET. See: https://aka.ms/dotnet-support-policy
  BlazorApp -> C:UsersdarothDesktopBlazorAppbinDebugnet7.0BlazorApp.dll
dotnet watch 🚀 Started
info: Microsoft.Hosting.Lifetime[14]
      Now listening on: https://localhost:7148
info: Microsoft.Hosting.Lifetime[14]
      Now listening on: http://localhost:5041
info: Microsoft.Hosting.Lifetime[0]
      Application started. Press Ctrl+C to shut down.
info: Microsoft.Hosting.Lifetime[0]
      Hosting environment: Development
info: Microsoft.Hosting.Lifetime[0]
      Content root path: C:UsersdarothDesktopBlazorApp
dotnet watch ⌚ File changed: .PagesIndex.razor.
dotnet watch 🔥 Hot reload of changes succeeded.
info: Microsoft.Hosting.Lifetime[0]
      Application is shutting down...
dotnet watch 🛑 Shutdown requested. Press Ctrl+C again to force exit.

Configure dotnet watch to always restart for rude editing

By placing DOTNET_ WATCH_ RESTART_ ON_ RUDE_ The EDIT environment variable is set to true, and dotnet watch is configured to always restart without prompting for rude edits (edits that cannot be reloaded hot).

Injecting services into custom validation properties in Blazor

You can now inject services into custom validation properties in Blazor. Blazor will set the ValidationContext so that it can be used as a service provider.

public class SaladChefValidatorAttribute : ValidationAttribute
{
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        var saladChef = validationContext.GetRequiredService();
 if (saladChef.ThingsYouCanPutInASalad.Contains(value.ToString()))
 {
 return ValidationResult.Success;
 }
 return new ValidationResult("You should not put that in a salad!");
 }
}

// Simple class configured as a service for dependency injection
public class SaladChef
{
 public string[] ThingsYouCanPutInASalad = { "Strawberries", "Pineapple", "Honeydew", "Watermelon", "Grapes" };
}

Thanks to @MariovanZeist for your contribution!

Faster header parsing and writing

We have made several improvements to header parsing and writing performance for HTTP/2 and HTTP/3. For more information, see the following pull-down requests:

gRPC JSON Transcoding

GRPC JSON transcoding allows the gRPC service to be used like the RESTful HTTP API. Once configured, gRPC JSON transcoding allows you to invoke gRPC methods using familiar HTTP concepts:

  • HTTP Verbs
  • URL parameter binding
  • JSON Request/Response

Of course, gRPC can continue to be used. RESTful API for gRPC services. No repetition!

ASP.NET Core provides experimental support for this functionality using a library called the gRPC HTTP API. For. NET 7, we plan to use this feature as ASP. The supported part of NET Core. This feature is not yet included. NET 7, but you can try out existing lab packages. For more information, see Getting Started Documentation for gRPC HTTP API.

Give Feedback

We hope you like it. ASP in NET 7. NET Core Preview, and you're for us. NET 7 roadmap is as exciting as we are! We would like to hear about your experience with this version and your view of the roadmap. By GitHub Submit questions and comments on Road Map Issues Let us know what you think.

Thank you for trying out ASP.NET Core!

Text Link

ASP.NET Core updates in .NET 7 Preview 1

This work uses Knowledge Sharing Attribution-Non-Commercial Use-Sharing 4.0 International License Agreement in the Same Way License.

You are welcome to reprint, use and republish the article, but you must keep the article's signature Zheng Ziming (including links: https://blog.csdn.net/MingsonZheng/ ) must not be used for commercial purposes. Works modified in this article must be published under the same license.

If you have any questions, please contact me ( MingsonZheng@outlook.com).

Topics: Python ASP.NET Back-end .NET computer