Configure 函数中的内容,可以直接写在 var app = builder.Build(); 代码之后。
所以,本文之前的代码,可以直接转换为:
using Azure.Messaging.WebPubSub; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Azure; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; var ConnectionString = ""; var builder = WebApplication.CreateBuilder(args); builder.Services.AddAzureClients(builder => { builder.AddWebPubSubServiceClient(ConnectionString, "stream"); }); var app = builder.Build(); if (!app.Environment.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseStaticFiles(); app.UseRouting(); app.UseEndpoints(endpoints => { endpoints.MapGet("/negotiate", async context => { var service = context.RequestServices.GetRequiredService<WebPubSubServiceClient>(); var response = new { url = service.GetClientAccessUri(roles: newstring[] { "webpubsub.sendToGroup.stream", "webpubsub.joinLeaveGroup.stream" }).AbsoluteUri }; await context.Response.WriteAsJsonAsync(response); }); }); app.MapGet("/", () => "Hello World!"); app.Run();
特别注意,在新模板下的代码,非常容易出现:CS8803 : Top-level statements must precede namespace and type declarations 错误。这是因为 .NET 6.0在隐藏了Main函数后,在编译代码时候,会自动补上Main函数,所以在Program.cs 的代码中,如果需要定义其他类,必须放在文件的末尾,不能在文件开头部分和中间。