如何在.NET 6/7中从startup.cs使用program.cs?

huangapple go评论72阅读模式
英文:

How to use program.cs from startup.cs in .NET 6/7?

问题

以下是startup.cs的翻译部分:

using System;
using AutoMapper;
using fixit.Data;
using fixit.Models;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

using System.Text;

// using Pomelo.EntityFrameworkCore.MySql;
// using fixit.Service;

namespace fixit
{   
    public class Startup
    {   
        readonly string AllowedOrigin = "allowedOrigin";

        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // 此方法由运行时调用。使用此方法将服务添加到容器中。
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<DataContext>(opt => opt.UseSqlServer(Configuration.GetConnectionString("fixItConnection")));
            services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());

           services.AddCors(option =>
            {
                option.AddPolicy("allowedOrigin",
                    builder => builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader()
                    );
            });

            services.AddControllers();

            services.AddScoped<IRepository<Service>, ServiceRepository>();
        }

        // 此方法由运行时调用。使用此方法配置HTTP请求管道。
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseCors(AllowedOrigin);
            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseAuthentication();
            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
}

以下是program.cs的翻译部分:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

namespace fixit
{
    public class Program
    {
        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                });
    }
}

至于您的问题,您提到尝试将program.cs迁移到.NET 6,但应用程序无法构建。要解决这个问题,您需要确保已按照.NET 6的新要求进行了修改。这可能涉及更改引用、命名空间和配置,以适应.NET 6的新架构。您可以参考.NET 6的官方文档和迁移指南来了解详细信息,并根据需要进行调整和修复。

英文:

I try to follow a tutorial online how to integrate Flutter with an ASP.NET Core Web API, the problem is the tutorial is outdated and requires me to create an ASP.NET Core 6 instead of 5.

This is code from startup.cs that been deprecated in .NET 6:

using System;
using AutoMapper;
using fixit.Data;
using fixit.Models;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

using System.Text;

// using Pomelo.EntityFrameworkCore.MySql;
// using fixit.Service;

namespace fixit
{   
    public class Startup
    {   
        readonly string AllowedOrigin = &quot;allowedOrigin&quot;;

        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext&lt;DataContext&gt;(opt =&gt; opt.UseSqlServer(Configuration.GetConnectionString(&quot;fixItConnection&quot;)));
            services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());

           services.AddCors(option =&gt;
            {
                option.AddPolicy(&quot;allowedOrigin&quot;,
                    builder =&gt; builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader()
                    );
            });

            services.AddControllers();

            services.AddScoped&lt;IRepository&lt;Service&gt;, ServiceRepository&gt;();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseCors(AllowedOrigin);
            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseAuthentication();
            app.UseAuthorization();

            app.UseEndpoints(endpoints =&gt;
            {
                endpoints.MapControllers();
            });
        }
    }
}

And this is program.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

namespace fixit
{
    public class Program
    {
        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =&gt;
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =&gt;
                {
                    webBuilder.UseStartup&lt;Startup&gt;();
                });
    }
}

I tried to write program.cs in .NET 6, but the app can't be built.

This is my program.cs:

using fixit.Data;
using fixit.Models;
using Microsoft.Data.SqlClient;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddControllers();
builder.Services.AddScoped&lt;IRepository&lt;Service&gt;, ServiceRepository&gt;();

builder.Services.AddCors(option =&gt;
  {
      option.AddPolicy(&quot;allowedOrigin&quot;,
          builder =&gt; builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader()
          );
  });

var app = builder.Build();

// For production scenarios, consider keeping Swagger configurations behind the environment check
// if (app.Environment.IsDevelopment())
// {
    app.UseSwagger();
    app.UseSwaggerUI();
// }

app.UseHttpsRedirection();

string connectionString = app.Configuration.GetConnectionString(&quot;AZURE_SQL_CONNECTIONSTRING&quot;)!;

try
{
    // Table would be created ahead of time in production
    using var conn = new SqlConnection(connectionString);
    conn.Open();

    var command = new SqlCommand(
        &quot;CREATE TABLE Service (ID int NOT NULL PRIMARY KEY IDENTITY, servicename varchar(255), description varchar(255), category varchar(255), initialprice );&quot;,
        conn);
    using SqlDataReader reader = command.ExecuteReader();
}
catch (Exception e)
{
    // Table may already exist
    Console.WriteLine(e.Message);
}

app.MapGet(&quot;/Service&quot;, () =&gt; {
    var rows = new List&lt;string&gt;();

    using var conn = new SqlConnection(connectionString);
    conn.Open();

    var command = new SqlCommand(&quot;SELECT * FROM Service&quot;, conn);
    using SqlDataReader reader = command.ExecuteReader();

    if (reader.HasRows)
    {
        while (reader.Read())
        {
            rows.Add($&quot;{reader.GetInt32(0)}, {reader.GetString(1)}, {reader.GetString(2)}&quot;);
        }
    }

    return rows;
})
.WithName(&quot;GetPersons&quot;)
.WithOpenApi();

app.MapPost(&quot;/Service&quot;, (Service person) =&gt; {
    using var conn = new SqlConnection(connectionString);
    conn.Open();

    var command = new SqlCommand(
        $&quot;INSERT INTO Service (serviceid, servicename, description, category,initialprice,intermediateprice,advanceprice) VALUES (&#39;{person.ServiceId}&#39;, &#39;{person.ServiceName}&#39;,&#39;{person.Description}&#39;,&#39;{person.Category}&#39;,&#39;{person.InitialPrice}&#39;,&#39;{person.IntermediatePrice}&#39;,&#39;{person.AdvancedPrice}&#39;)&quot;,
        conn);

    using SqlDataReader reader = command.ExecuteReader();
})
.WithName(&quot;CreatePerson&quot;)
.WithOpenApi();

app.Run();

How to solve this?

答案1

得分: 1

请参考此文档,如果您想在最小 API 中使用 .WithOpenApi(),您需要使用.Net 7而不是.Net 6

从您的代码中,您似乎想要使用最小 API 而不是控制器 API,因此在创建 Web API 项目模板时,您可以取消选中此选项以创建最小 API:

如何在.NET 6/7中从startup.cs使用program.cs?

在这里,我修改了您的一些代码,以使其可执行演示,希望它可以为您提供一些帮助。

Model

public class Service
{
    public string ServiceName { get; set; }
    public string Description { get; set; }
    public string Category { get; set; }
    public int InitialPrice { get; set; }
    public int IntermediatePrice { get; set; }
    public int AdvancedPrice { get; set; }
}

Program.cs

using Microsoft.Data.SqlClient;

namespace MinmalApi
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var MyAllowSpecificOrigins = "_myAllowSpecificOrigins";
            var builder = WebApplication.CreateBuilder(args);

            // Add services to the container.
            builder.Services.AddAuthorization();

            // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
            builder.Services.AddEndpointsApiExplorer();
            builder.Services.AddSwaggerGen();
            builder.Services.AddCors(option =>
            {
                option.AddPolicy("MyAllowSpecificOrigins",
                    builder => builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader()
                    );
            });

            //register other service.

            var app = builder.Build();

            // Configure the HTTP request pipeline.
            if (app.Environment.IsDevelopment())
            {
                app.UseSwagger();
                app.UseSwaggerUI();
            }

            app.UseHttpsRedirection();

            app.UseCors(MyAllowSpecificOrigins);

            string connectionString = app.Configuration.GetConnectionString("default")!;

            try
            {
                // Table would be created ahead of time in production
                using var conn = new SqlConnection(connectionString);
                conn.Open();

                var command = new SqlCommand(
                    "CREATE TABLE Service (ID int NOT NULL PRIMARY KEY IDENTITY, servicename varchar(255), description varchar(255), category varchar(255), initialprice int,IntermediatePrice int,AdvancedPrice int);",
                    conn);
                using SqlDataReader reader = command.ExecuteReader();
            }
            catch (Exception e)
            {
                // Table may already exist
                Console.WriteLine(e.Message);
            }

            app.MapGet("/Service", () =>
            {
                var rows = new List<string>();

                using var conn = new SqlConnection(connectionString);
                conn.Open();

                var command = new SqlCommand("SELECT * FROM Service", conn);
                using SqlDataReader reader = command.ExecuteReader();

                if (reader.HasRows)
                {
                    while (reader.Read())
                    {
                        rows.Add($"{reader.GetInt32(0)}, {reader.GetString(1)}, {reader.GetString(2)}");
                    }
                }

                return rows;
            })
            .WithName("GetPersons");

            app.MapPost("/Service", (Service person) =>
            {
                using var conn = new SqlConnection(connectionString);
                conn.Open();

                var command = new SqlCommand(
                    $"INSERT INTO Service ( servicename, description, category,initialprice,IntermediatePrice,AdvancedPrice) VALUES ('{person.ServiceName}','{person.Description}','{person.Category}','{person.InitialPrice}','{person.IntermediatePrice}','{person.AdvancedPrice}')",
                    conn);

                using SqlDataReader reader = command.ExecuteReader();
            })
            .WithName("CreatePerson");

            app.Run();
        }
    }
}

Gif 演示

如何在.NET 6/7中从startup.cs使用program.cs?

从 gif 演示中,您可以看到所有端点都正常工作。

英文:

Refer to this Docs, If you wanna use .WithOpenApi() in minimal API, You need to use .Net 7 instead of .Net6.

From your code, You seem to wanna use Minimal api instead of controller Api, So when you create Web Api project with template, You can uncheck this option to create a minimal api:

如何在.NET 6/7中从startup.cs使用program.cs?

Here I modified some of your code to make it executable demo, Hope it can give you some help.

Model

public class Service
{
public string ServiceName { get; set; }
public string Description { get; set; }
public string Category { get; set; }
public int InitialPrice { get; set; }
public int IntermediatePrice { get; set; }
public int AdvancedPrice { get; set; }
}

Program.cs

using Microsoft.Data.SqlClient;
namespace MinmalApi
{
public class Program
{
public static void Main(string[] args)
{
var MyAllowSpecificOrigins = &quot;_myAllowSpecificOrigins&quot;;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddAuthorization();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddCors(option =&gt;
{
option.AddPolicy(&quot;MyAllowSpecificOrigins&quot;,
builder =&gt; builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader()
);
});
//register other service.
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseCors(MyAllowSpecificOrigins);
string connectionString = app.Configuration.GetConnectionString(&quot;default&quot;)!;
try
{
// Table would be created ahead of time in production
using var conn = new SqlConnection(connectionString);
conn.Open();
var command = new SqlCommand(
&quot;CREATE TABLE Service (ID int NOT NULL PRIMARY KEY IDENTITY, servicename varchar(255), description varchar(255), category varchar(255), initialprice int,IntermediatePrice int,AdvancedPrice int);&quot;,
conn);
using SqlDataReader reader = command.ExecuteReader();
}
catch (Exception e)
{
// Table may already exist
Console.WriteLine(e.Message);
}
app.MapGet(&quot;/Service&quot;, () =&gt;
{
var rows = new List&lt;string&gt;();
using var conn = new SqlConnection(connectionString);
conn.Open();
var command = new SqlCommand(&quot;SELECT * FROM Service&quot;, conn);
using SqlDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
rows.Add($&quot;{reader.GetInt32(0)}, {reader.GetString(1)}, {reader.GetString(2)}&quot;);
}
}
return rows;
})
.WithName(&quot;GetPersons&quot;);
app.MapPost(&quot;/Service&quot;, (Service person) =&gt;
{
using var conn = new SqlConnection(connectionString);
conn.Open();
var command = new SqlCommand(
$&quot;INSERT INTO Service ( servicename, description, category,initialprice,IntermediatePrice,AdvancedPrice) VALUES (&#39;{person.ServiceName}&#39;,&#39;{person.Description}&#39;,&#39;{person.Category}&#39;,&#39;{person.InitialPrice}&#39;,&#39;{person.IntermediatePrice}&#39;,&#39;{person.AdvancedPrice}&#39;)&quot;,
conn);
using SqlDataReader reader = command.ExecuteReader();
})
.WithName(&quot;CreatePerson&quot;);
app.Run();
}
}
}

Gif Demo

如何在.NET 6/7中从startup.cs使用program.cs?

From the gif demo you can see that all endpoints are working fine.

huangapple
  • 本文由 发表于 2023年5月11日 09:46:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/76223612.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定