```csharp
// program.cs
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
//builder.Services
// .AddControllers(options => options.RespectBrowserAcceptHeader = true)
// .AddXmlSerializerFormatters();
//========================================
var app = builder.Build();
app.MapControllers();
app.Run();
// opera.cs
public class Opera
{
public int OperaID { get; set; }
public string? Title { get; set; }
public int? Year { get; set; }
public string? Composer { get; set; }
}
// operacontroller.cs
[Route("api/[controller]")]
[ApiController]
public class OperaController : ControllerBase
{
[HttpGet]
public Opera Get()
{
Opera opera = new Opera {
OperaID = 1,
Title = "尤麗狄西",
Year = 1600,
Composer = "佩里"
};
return opera;
}
}
//======================================
// .csproj
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="6.*" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="6.*">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
</ItemGroup>
//==========================
// operacontext.cs
public class OperaContext:DbContext
{
public OperaContext(DbContextOptions<OperaContext> options)
:base(options)
{
}
public DbSet<Opera> Operas { get; set; } = null!;
}
// appsettings.Development.json
{
"ConnectionStrings": {
"default": "server=(localdb)\\mssqllocaldb;database=mod15db;trusted_connection=true;"
},
// program.cs
using Microsoft.EntityFrameworkCore;
using WebApiDemo.Models;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
//Console.WriteLine(builder.Configuration.GetConnectionString("default"));
builder.Services.AddDbContext<OperaContext>(options=>options.UseSqlServer(
builder.Configuration.GetConnectionString("default")
));
var app = builder.Build();
app.MapControllers();
app.Run();
//=========================
// PMC
PM> Add-Migration Initial
PM> Update-Database
//============================
new(){
OperaID = 1,
Title = "Cosi Fan Tutte",
Year = 1790,
Composer = "Wolfgang Amadeus Mozart",
},
new(){
OperaID = 2,
Title = "Rigoletto",
Year = 1851,
Composer = "Giuseppe Verdi",
},
new(){
OperaID = 3,
Title = "Nixon in China",
Year = 1987,
Composer = "John Adams"
},
new(){
OperaID = 4,
Title = "Wozzeck",
Year = 1922,
Composer = "Alban Berg"
}
//===========================
// operacontext.cs
public class OperaContext:DbContext
{
public OperaContext(DbContextOptions<OperaContext> options)
:base(options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Opera>().HasData(
new()
{
OperaID = 1,
Title = "Cosi Fan Tutte",
Year = 1790,
Composer = "Wolfgang Amadeus Mozart",
},
new()
{
OperaID = 2,
Title = "Rigoletto",
Year = 1851,
Composer = "Giuseppe Verdi",
},
new()
{
OperaID = 3,
Title = "Nixon in China",
Year = 1987,
Composer = "John Adams"
},
new()
{
OperaID = 4,
Title = "Wozzeck",
Year = 1922,
Composer = "Alban Berg"
},
new()
{
OperaID = 5,
Title = "Cosi Fan Tutte2",
Year = 1790,
Composer = "Wolfgang Amadeus Mozart",
},
new()
{
OperaID = 6,
Title = "Rigoletto2",
Year = 1851,
Composer = "Giuseppe Verdi",
},
new()
{
OperaID = 7,
Title = "Nixon in China2",
Year = 1987,
Composer = "John Adams"
},
new()
{
OperaID = 8,
Title = "Wozzeck2",
Year = 1922,
Composer = "Alban Berg"
});
}
public DbSet<Opera> Operas { get; set; } = null!;
}
// PMC
PM> add-migration SeedData2
PM> update-database
//===================================
// OperasController.cs
[Route("api/[controller]")]
[ApiController]
public class OperasController : ControllerBase
{
readonly OperaContext _context;
public OperasController(OperaContext context)
{
_context = context;
}
// GET: api/<OperasController>
[HttpGet]
public IEnumerable<Opera> Get()
{
return _context.Operas.ToList();
}
//====================================
// operascontroller.cs
[HttpGet]
public async Task< IEnumerable<Opera>> Get()
{
return await _context.Operas.ToListAsync();
}
[HttpGet("{id}")]
public async Task<ActionResult<Opera>> Get(int id)
{
Opera? opera = await _context.Operas.FindAsync(id);
if (opera == null) return NotFound();
return opera;
}
[HttpPost]
public async Task<IActionResult> Post([FromForm] Opera opera)
{
_context.Add(opera);
await _context.SaveChangesAsync();
return CreatedAtAction(nameof(Get),
new { id = opera.OperaID }, opera);
}
[HttpPut("{id}")]
public async Task<IActionResult> Put(int id,[FromForm] Opera opera)
{
if (id != opera.OperaID) return BadRequest();
//var item = await _context.Operas.FindAsync(id);
//if (item == null) return NotFound();
//item.Title = opera.Title;
//item.Year = opera.Year;
//_context.Update(opera);
await _context.SaveChangesAsync();
return NoContent();
}
[HttpDelete("{id}")]
public async Task<IActionResult> Delete(int id)
{
var opera = await _context.Operas.FindAsync(id);
if (opera == null) return NotFound();
_context.Remove(opera);
await _context.SaveChangesAsync();
return NoContent();
}
//==============================
// .csproj
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.4.0" />
// program.cs
using Microsoft.EntityFrameworkCore;
using WebApiDemo.Models;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.AddSwaggerGen();
builder.Services.AddDbContext<OperaContext>(options=>options.UseSqlServer(
builder.Configuration.GetConnectionString("default")
));
var app = builder.Build();
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.MapControllers();
app.Run();
//==============================
// MVC5 Project
// opera.cs
public class Opera
{
public int OperaID { get; set; }
public string Title { get; set; }
public int? Year { get; set; }
public string Composer { get; set; }
}
// operainfoController.cs
public class OperaInfoController : Controller
{
// GET: OperaInfo
public ActionResult Index()
{
return View();
}
}
// shared/_layout.cshtml
<li>@Html.ActionLink("Opera Info", "Index", "OperaInfo", new { area = "" }, new { @class = "nav-link" })</li>
// operainfo/index.cshtml
@model MVC5WebSite.Models.Opera
@{
ViewBag.Title = "Opera Info";
}
<h2>Opera Info</h2>
<form id="form1">
@Html.EditorForModel()
</form>
<hr />
<div>
<input type="button" id="btnAll" value="List" />
<input type="button" id="btnGet" value="Get" />
<input type="button" id="btnInsert" value="Insert" />
<input type="button" id="btnUpdate" value="Update" />
<input type="button" id="btnDelete" value="Delete" />
</div>
<ul id="list"></ul>
//==================================
//web.config
<appSettings>
<add key="webapilocatoin" value="http://localhost:5226/api/operas" />
// operainfo/index.cshtml
@using System.Configuration
@model MVC5WebSite.Models.Opera
@{
ViewBag.Title = "Opera Info";
string path = ConfigurationManager.AppSettings["webapilocatoin"];
}
<h2>Opera Info - @path</h2>
//=====================
// operainfo/index.cshtml
@section scripts{
<script>
$(() => {
async function getAll() {
var response = await fetch("@path");
var result = await response.json();
console.log(Array.isArray(result));
}
$("#btnAll").on("click", getAll);
});
</script>
}
//==========================
//CORS enable
// program.cs
using Microsoft.EntityFrameworkCore;
using WebApiDemo.Models;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.AddSwaggerGen();
builder.Services.AddDbContext<OperaContext>(options=>options.UseSqlServer(
builder.Configuration.GetConnectionString("default")
));
builder.Services.AddCors(options =>
{
options.AddPolicy("CorsPolicy",
builder => builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader());
});
var app = builder.Build();
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseCors("CorsPolicy");
app.MapControllers();
app.Run();
//==============================
// appsettings.development.json
{
"corsweb": "http://localhost:51512",
"ConnectionStrings": {
"default": "server=(localdb)\\mssqllocaldb;database=mod15db;trusted_connection=true;"
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
}
}
// program.cs
using Microsoft.EntityFrameworkCore;
using WebApiDemo.Models;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.AddSwaggerGen();
builder.Services.AddDbContext<OperaContext>(options=>options.UseSqlServer(
builder.Configuration.GetConnectionString("default")
));
Console.WriteLine(builder.Configuration["corsweb"]);
builder.Services.AddCors(options =>
{
options.AddPolicy("CorsPolicy",
o => o.WithOrigins(builder.Configuration["corsweb"])
.AllowAnyMethod()
.AllowAnyHeader());
});
var app = builder.Build();
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseCors("CorsPolicy");
app.MapControllers();
app.Run();
//=========================
// operainfo/index.cshtml
@section scripts{
<script>
$(() => {
var path="@path";
async function getAll() {
$("#list").empty();
var response = await fetch(path);
var result = await response.json();
result.forEach(item => {
$("#list").append(`<li>${item.operaID}---${item.title}</li>`);
});
}
$("#btnAll").on("click", getAll);
$("#btnGet").on("click", () => {
//alert(`${path}/${$("#OperaID").val()}`);
fetch(`${path}/${$("#OperaID").val()}`)
.then(response => response.json())
.then(item => {
$("#Title").val(item.title);
$("#Year").val(item.year);
$("#Composer").val(item.composer);
});
});
});
</script>
}
//==============================
// operainfo/index.cshtml
$("#btnGet").on("click", () => {
//alert(`${path}/${$("#OperaID").val()}`);
fetch(`${path}/${$("#OperaID").val()}`)
.then(response => {
if (response.ok) {
return response.json();
} else {
throw response.statusText;
}
})
.then(item => {
$("#Title").val(item.title);
$("#Year").val(item.year);
$("#Composer").val(item.composer);
})
.catch(error=>alert(error));
});
$("#btnInsert").on("click", () => {
//alert($("#form1").serialize());
//alert(`title=${$("#Title").val()}&year=${$("#Year").val()}&composer=${$("#Composer").val()}`);
fetch(path, {
method: "post",
headers: {
"content-type":"application/x-www-form-urlencoded"
},
body: `title=${$("#Title").val()}&year=${$("#Year").val()}&composer=${$("#Composer").val() }`
//body: $("#form1").serialize()
}).then(getAll);
});
$("#btnDelete").on("click", () => {
fetch(`${path}/${$("#OperaID").val()}`, {
method: "delete"
}).then(getAll);
});
$("#btnUpdate").on("click", () => {
fetch(`${path}/${$("#OperaID").val()}`, {
method: "put",
headers: {
"content-type": "application/x-www-form-urlencoded"
},
body: $("#form1").serialize()
}).then(getAll);
});
//=========================================
// appsettings.development.json
{
"corsweb": "http://localhost:51512",
"ConnectionStrings": {
"default": "server=(localdb)\\mssqllocaldb;database=mod15db;trusted_connection=true;"
},
// appsettings.json
{
"corsweb": "http://server1:51512",
"ConnectionStrings": {
"default": "server=server1;database=mod15db;trusted_connection=true;"
},
// program.cs
Console.WriteLine(builder.Configuration.GetConnectionString("default"));
Console.WriteLine(builder.Configuration["corsweb"]);
//=============================================
// PMC
PM> scaffold-dbcontext -connection "server=(localdb)\mssqllocaldb;database=mydatabase;trusted_connection=true;" -provider Microsoft.EntityFrameworkCore.SqlServer -outputdir Models -tables Products, Categories -context MyContext -dataannotation
//===============================
//web.release.config
<appSettings>
<add key="webapilocatoin" value="http://Server1:9999/api/operas"
xdt:Transform="SetAttributes" xdt:Locator="Match(key)"/>
</appSettings>
```