ASP.NET Core +API+Swagger+MVC实例
1、打开VS2019,创建一个空白的解决方案
2、添加新建项目,选择类库(.NET Core)
3、 点击右键选择管理NuGet程序包
4、.导入EF Core相关包
Microsoft.EntityFrameworkCore.SqlServer:Sql Server数据库EF提供程序
Microsoft.EntityFrameworkCore.Design:设计时EF共享库
Microsoft.EntityFrameworkCore.Tools:EF的NuGet包管理器命令工具
5、选择工具的NuGet包管理→程序包管理器控制台
6、执行NuGet命令,通过数据库生成实体模型
Scaffold-DbContext ‘Data Source=.;Initial Catalog=ShoppingDB; Integrated Security=True;’ Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models -Context ShopContext
7、添加命名空间和不序列化的属性
8、接下来创建APT,把高级处的为HTTPS勾选去掉
9、找到appsettings.json文件,添加依赖注入配置
“ConnectionStrings”: {
“shopdb”: “Data Source=.;Initial Catalog=ShoppingDB;Integrated Security=True”
},
10、找到Startup.cs 文件,在ConfigureServices方法里添加
//注册上下文
services.AddDbContext(option =>
{
option.UseSqlServer(Configuration.GetConnectionString(“shopdb”));
});
11、创建控制器,选择其操作使用Entity Framework的API控制器
12、选择上下文类和模型类
13、添加swagger的管理程序包,选择第一个
14、结下来在Startup.cs的ConfigureServices方法里面添加
//注册Swagger生成器
services.AddSwaggerGen(opti =>
{
opti.SwaggerDoc(“v1”, new OpenApiInfo
{
Title = “Shop API”,
Version = “v1”
});
}
);
15、在Startup.cs的Configure方法里面添加//静态文件查看中间件
app.UseStaticFiles();
//Swagger中间件
app.UseSwagger();
//SwaggerUI中间件
app.UseSwaggerUI(option =>
{
option.SwaggerEndpoint("/swagger/v1/swagger.json", “Shop API v1”);
});
16、运行不调试API程序,输入http://localhost:5000/api/Product,API接口OK了
17、输入http://localhost:5000/swagger/index.html,可以看到swagger的文档,以及API写好的方法
18、重点是打开http://localhost:5000/swagger/v1/swagger.json能否正常显示,后面其它地方需要调用
19、创建一个asp.net Core MVC 点右键添加服务引用,选择OpenAPI,点击添加新的服务引用,在URL里面输入上面查看的http://localhost:5000/swagger/v1/swagger.json,在输入命名空间
图片
20、在HomeController添加using MyShop;的引用
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using SwaggerShopUI.Models;
using System.Net.Http;
using MyShop;
namespace SwaggerShopUI.Controllers
{
public class HomeController : Controller
{
private readonly ILogger _logger;
public HomeController(ILogger<HomeController> logger)
{
_logger = logger;
}
// 查询全部商品数据
public async Task<IActionResult> Index()
{
var client = new swaggerClient("http://localhost:5000/", new HttpClient());
var pro = await client.ProductsAllAsync();
return View(pro);
}
//添加商品
[HttpGet]
public async Task<IActionResult> Add()
{
var client = new swaggerClient("http://localhost:5000/", new HttpClient());
var pro = await client.CategoriesAllAsync();
return View(pro);
}
//添加商品
[HttpPost]
public async Task<IActionResult> Add(Products p)
{
var client = new swaggerClient("http://localhost:5000/", new HttpClient());
var pro = await client.ProductsAsync(p);
return RedirectToAction("Index");
}
//修改商品
[HttpGet]
public async Task<IActionResult> Edit(int id)
{
var client = new swaggerClient("http://localhost:5000/", new HttpClient());
ViewBag.Categories=await client.CategoriesAllAsync();
var pro =await client.Products2Async(id);
return View(pro);
}
//修改商品
[HttpPost]
public async Task<IActionResult> Edit(Products p)
{
var client = new swaggerClient("http://localhost:5000/", new HttpClient());
await client.Products3Async(p.ProductId,p);
return RedirectToAction("Index");
}
//删除
public async Task<IActionResult> Remove(int id)
{
var client = new swaggerClient("http://localhost:5000/", new HttpClient());
var pro = await client.Products4Async(id);
return RedirectToAction("Index");
}
public IActionResult Privacy()
{
return View();
}
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
}
}
对应的view视图代码:
首页:Index.cshtml
@{
ViewData[“Title”] = “Home Page”;
}
<tr>
<th>编号</th>
<th>名称</th>
<th>类别</th>
<th>价格</th>
<th>库存</th>
<th>描述</th><th>操作</th>
</tr>
</thead>
@foreach (var item in Model)
{
<tr>
<td>@item.ProductId</td>
<td>@item.ProductName</td>
<td>@item.CategoryId + [@item.Category.CategoryName]</td>
<td>@string.Format("{0:C}", @item.ProductPrice)</td>
<td>@item.Stock</td>
<td>@item.ProductDesc</td>
<td>
@Html.ActionLink("编辑", "Edit", "Home", new { id = item.ProductId },new { @class = "btn btn-primary" })
@Html.ActionLink("删除", "Remove", "Home", new { id = item.ProductId }, new { @class = "btn btn-primary", onclick = "return confirm('确认删除?')" })
</td>
</tr>
}
</table>
@{
ViewData[“Title”] = “添加数据”;
}
添加数据
@using (Html.BeginForm("Add", "Home", FormMethod.Post)) {
<select name="CategoryId" class="form-control">
@foreach (var item in Model)
{
<option value="@item.CategoryId">@item.CategoryName</option>
}
</select>
</p>
<p><label>库存</label><input type="number" name="Stock" placeholder="请输入商品库存" class="form-control" value="" /></p>
<p><label>描述</label><input type="text" name="ProductDesc" placeholder="请输入商品描述" class="form-control" value="" /></p>
<p><input type="submit" name="name" value="保存" class="btn btn-primary" /></p>
}
修改的页面:Edit.cshtml
@model MyShop.Products
@{
ViewData[“Title”] = “修改数据”;
}
修改数据
@using (Html.BeginForm("Edit", "Home", FormMethod.Post)) {@Html.HiddenFor(model => model.ProductId)
@Html.EditorFor(model => model.ProductName, new { htmlAttributes = new { @class = "form-control", placeholder = "请输入商品名称" } })
</p>
<p>
<label>价格</label>
@Html.EditorFor(model => model.ProductPrice, new { htmlAttributes = new { @class = "form-control", placeholder = "请输入商品价格" } })
</p>
<p>
<label>类别</label>
<select name="CategoryId" class="form-control">
@foreach (var item in ViewBag.Categories)
{
<option value="@item.CategoryId">@item.CategoryName</option>
}
</select>
</p>
<p>
<label>库存</label>
@Html.EditorFor(model => model.Stock, new { htmlAttributes = new { @class = "form-control", placeholder = "请输入商品库存" } })
</p>
<p>
<label>描述</label>
@Html.EditorFor(model => model.ProductDesc, new { htmlAttributes = new { @class = "form-control", placeholder = "请输入商品库存" } })
</p>
<p><input type="submit" name="name" value="保存" class="btn btn-primary" /></p>
}
先把API设置为启动项,选择开始执行不调试,接下来在选择MVC作为启动项,选择开始执行不调试
图片
上一篇: 批量改文件名小程序里的几个“坑”
下一篇: 轻松掌握Java状态模式