英文:
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 = "allowedOrigin";
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<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>();
}
// 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 =>
{
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) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
}
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<IRepository<Service>, ServiceRepository>();
builder.Services.AddCors(option =>
{
option.AddPolicy("allowedOrigin",
builder => 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("AZURE_SQL_CONNECTIONSTRING")!;
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 );",
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")
.WithOpenApi();
app.MapPost("/Service", (Service person) => {
using var conn = new SqlConnection(connectionString);
conn.Open();
var command = new SqlCommand(
$"INSERT INTO Service (serviceid, servicename, description, category,initialprice,intermediateprice,advanceprice) VALUES ('{person.ServiceId}', '{person.ServiceName}','{person.Description}','{person.Category}','{person.InitialPrice}','{person.IntermediatePrice}','{person.AdvancedPrice}')",
conn);
using SqlDataReader reader = command.ExecuteReader();
})
.WithName("CreatePerson")
.WithOpenApi();
app.Run();
How to solve this?
答案1
得分: 1
请参考此文档,如果您想在最小 API 中使用 .WithOpenApi()
,您需要使用.Net 7
而不是.Net 6
。
从您的代码中,您似乎想要使用最小 API 而不是控制器 API,因此在创建 Web API 项目模板时,您可以取消选中此选项以创建最小 API:
在这里,我修改了您的一些代码,以使其可执行演示,希望它可以为您提供一些帮助。
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 演示
从 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:
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 = "_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 Demo
From the gif demo you can see that all endpoints are working fine.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论