欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

ASP.NET Core +API+Swagger+MVC实例

程序员文章站 2024-03-13 12:27:51
...

1、打开VS2019,创建一个空白的解决方案
ASP.NET Core +API+Swagger+MVC实例
2、添加新建项目,选择类库(.NET Core)

ASP.NET Core +API+Swagger+MVC实例
3、 点击右键选择管理NuGet程序包
ASP.NET Core +API+Swagger+MVC实例
4、.导入EF Core相关包
Microsoft.EntityFrameworkCore.SqlServer:Sql Server数据库EF提供程序
Microsoft.EntityFrameworkCore.Design:设计时EF共享库
Microsoft.EntityFrameworkCore.Tools:EF的NuGet包管理器命令工具

ASP.NET Core +API+Swagger+MVC实例
5、选择工具的NuGet包管理→程序包管理器控制台
ASP.NET Core +API+Swagger+MVC实例
6、执行NuGet命令,通过数据库生成实体模型
Scaffold-DbContext ‘Data Source=.;Initial Catalog=ShoppingDB; Integrated Security=True;’ Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models -Context ShopContext

ASP.NET Core +API+Swagger+MVC实例
7、添加命名空间和不序列化的属性
ASP.NET Core +API+Swagger+MVC实例
8、接下来创建APT,把高级处的为HTTPS勾选去掉

ASP.NET Core +API+Swagger+MVC实例
9、找到appsettings.json文件,添加依赖注入配置
“ConnectionStrings”: {
“shopdb”: “Data Source=.;Initial Catalog=ShoppingDB;Integrated Security=True”
},

ASP.NET Core +API+Swagger+MVC实例
10、找到Startup.cs 文件,在ConfigureServices方法里添加
//注册上下文
services.AddDbContext(option =>
{
option.UseSqlServer(Configuration.GetConnectionString(“shopdb”));
});

11、创建控制器,选择其操作使用Entity Framework的API控制器
ASP.NET Core +API+Swagger+MVC实例
12、选择上下文类和模型类
ASP.NET Core +API+Swagger+MVC实例
13、添加swagger的管理程序包,选择第一个
ASP.NET Core +API+Swagger+MVC实例
14、结下来在Startup.cs的ConfigureServices方法里面添加
//注册Swagger生成器
services.AddSwaggerGen(opti =>
{
opti.SwaggerDoc(“v1”, new OpenApiInfo
{
Title = “Shop API”,
Version = “v1”
});
}
);
ASP.NET Core +API+Swagger+MVC实例

15、在Startup.cs的Configure方法里面添加//静态文件查看中间件
app.UseStaticFiles();
//Swagger中间件
app.UseSwagger();
//SwaggerUI中间件
app.UseSwaggerUI(option =>
{
option.SwaggerEndpoint("/swagger/v1/swagger.json", “Shop API v1”);
});

ASP.NET Core +API+Swagger+MVC实例
16、运行不调试API程序,输入http://localhost:5000/api/Product,API接口OK了
ASP.NET Core +API+Swagger+MVC实例
17、输入http://localhost:5000/swagger/index.html,可以看到swagger的文档,以及API写好的方法

ASP.NET Core +API+Swagger+MVC实例
18、重点是打开http://localhost:5000/swagger/v1/swagger.json能否正常显示,后面其它地方需要调用
ASP.NET Core +API+Swagger+MVC实例
19、创建一个asp.net Core MVC 点右键添加服务引用,选择OpenAPI,点击添加新的服务引用,在URL里面输入上面查看的http://localhost:5000/swagger/v1/swagger.json,在输入命名空间
图片

ASP.NET Core +API+Swagger+MVC实例
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”;
}

@Html.ActionLink("添加","Add","Home",null,new { @class="btn btn-primary"})
        <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>
添加页:Add.cshtml

@{
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作为启动项,选择开始执行不调试

图片