core api应用实例
,采用` core 3.1 + EF+mysql`
初始化项目`dotnet new webapi`,基于 `ASP.NET Core web API` 类型的项目,初始化文件如下
```C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace netCoreApiDemo
{
public class Startup
{
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.AddControllers();
}
// 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.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}
```
安装mysql相应的依赖
`dotnet add package Pomelo.EntityFrameworkCore.MySql`
安装完成之后编写`DBContext`
```C#
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace netCoreApiDemo.Models
{
public class AppContext:DbContext
{
public AppContext(DbContextOptions<AppContext> options)
:base(options)
{
}
}
}
```
配置`connectionString`
在`appsettings.json`文件中加入配置
`"ConnectionStrings": {
"DefaultConnection": MysqlConnStringmysql下载app
}`
在`startup.cs`文件的`ConfigureServices`方法中加入ConnectionString的配置。
```C#
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<AppContext>(options =>
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论