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

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

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

ASP.NET Core +API+Swagger+MVC实例_第4张图片
5、选择工具的NuGet包管理→程序包管理器控制台
ASP.NET Core +API+Swagger+MVC实例_第5张图片
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实例_第6张图片
7、添加命名空间和不序列化的属性
ASP.NET Core +API+Swagger+MVC实例_第7张图片
8、接下来创建APT,把高级处的为HTTPS勾选去掉

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

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

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

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实例_第14张图片
16、运行不调试API程序,输入http://localhost:5000/api/Product,API接口OK了
ASP.NET Core +API+Swagger+MVC实例_第15张图片
17、输入http://localhost:5000/swagger/index.html,可以看到swagger的文档,以及API写好的方法

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

ASP.NET Core +API+Swagger+MVC实例_第18张图片
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 logger)
    {
        _logger = logger;
    }

    // 查询全部商品数据
    public async Task Index()
    {
        var client = new swaggerClient("http://localhost:5000/", new HttpClient());
        var pro = await client.ProductsAllAsync();
        return View(pro);
    }
    //添加商品
    [HttpGet]
    public async Task Add()
    {
        var client = new swaggerClient("http://localhost:5000/", new HttpClient());
        var pro = await client.CategoriesAllAsync();          
        return View(pro);
    }
    //添加商品
    [HttpPost]
    public async Task 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 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 Edit(Products p)
    {
        var client = new swaggerClient("http://localhost:5000/", new HttpClient());
         await client.Products3Async(p.ProductId,p);
        return RedirectToAction("Index");
    }
    //删除
    public async Task 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"})
        
            编号
            名称
            类别
            价格
            库存
            描述操作
        
    
    @foreach (var item in Model)
    {
        
            @item.ProductId
            @item.ProductName
            @item.CategoryId + [@item.Category.CategoryName]
            @string.Format("{0:C}", @item.ProductPrice)
            @item.Stock
            @item.ProductDesc
            
                @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('确认删除?')" })
            
        
    }

添加页:Add.cshtml

@{
ViewData[“Title”] = “添加数据”;
}

添加数据

@using (Html.BeginForm("Add", "Home", FormMethod.Post)) {

名称

价格

类别

    

}

修改的页面: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 = "请输入商品名称" } })

@Html.EditorFor(model => model.ProductPrice, new { htmlAttributes = new { @class = "form-control", placeholder = "请输入商品价格" } })

@Html.EditorFor(model => model.Stock, new { htmlAttributes = new { @class = "form-control", placeholder = "请输入商品库存" } })

@Html.EditorFor(model => model.ProductDesc, new { htmlAttributes = new { @class = "form-control", placeholder = "请输入商品库存" } })

}

先把API设置为启动项,选择开始执行不调试,接下来在选择MVC作为启动项,选择开始执行不调试

图片

你可能感兴趣的:(.Net,Core,c#,数据库,sql)