个人练习实验:netcore webapi+swagger

个人做的一个练习,记录一下,只适合新手参考,不正确的地方多多批评指正。

 

说明的几个点:

1.关于MdOrg和DBMdOrg的说明

因为不想将数据库中的所有字段信息都面向用户,只想展示用户需要上传的字段,屏蔽对用户不需要的栏位,所有建了两个类:MdOrg主要是面向客户端调用,DBMdOrg继承MdOrg,主要是面向数据库进行操作(EF)。

确实没有找到其他的特性可以实现这种状况,暂时只想到使用继承。

 

2.关于MdOrg中的

[NotMapped]
public List<MdOrgSub1> detailList { set; get; }

这个假设的情况是用户上传资料的时候存在单头和单身的情况,一个单头对应多个单身,而在进行数据库操作的时候单头和单身是两种不同的表,使用[NotMapped]来告诉EF这个字段不映射到数据库中。大概是这样。

 

 

整个文件目录结构如下:

 

launchSettings.json

 

{
  "$schema": "http://json.schemastore.org/launchsettings.json",
  "iisSettings": {
    "windowsAuthentication": false, 
    "anonymousAuthentication": true, 
    "iisExpress": {
      "applicationUrl": "http://localhost:62789",
      "sslPort": 44340
    }
  },
  "profiles": {
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "launchUrl": "index.html",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
    "webapi": {
      "commandName": "Project",
      "launchBrowser": true,
      "launchUrl": "index.html",
      "applicationUrl": "https://localhost:5001;http://localhost:5000",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
  }
}

MdOrgController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using webapi.EF;
using webapi.Entity;
using webapi.Entity.DBEntity;
using webapi.Untils;

namespace webapi.Controllers
{
    /// <summary>
    /// 组织资料操作
    /// </summary>
    [Route("api/MdOrg")]
    [ApiController]
    public class MdOrgController : ControllerBase
    {


        
        /// <summary>
        /// 组织资料上传
        /// </summary>
        /// <param name="IdentityNo"></param>
        /// <param name="pmdorglist"></param>
        [HttpPost]
        [Route("addList")]
        public mResult addList(string IdentityNo,[FromBody] List<DBMdOrg> pmdorglist)
        {
            CheckID chk = new CheckID();
            mResult mret = new mResult();

            
            string chkret = chk.chkRights(IdentityNo, "localhost");
            if (chkret=="1")//存在权限的情况下继续
            {

                MyDBContext _context = new MyDBContext();
                List<MdOrg> listorg= _context.mdorg.ToList();



                //if (pmdorglist !=null)
                //{
                //    for (int i=0;i<pmdorglist.Count;i++)
                //    {
                //        MdOrg tmporg = pmdorglist[i];
                //        List<MdOrgSub1> orgsublist = tmporg.detailList;
                //        for (int j=0;j<orgsublist.Count;j++)
                //        {

                //        }
                //    }
                //}

                mret.flag = 1;
                mret.retMsg = "成功!";
            }
            else
            {
                mret.flag = 0;
                mret.retMsg = chkret;
            }
            return mret;
        }



        /// <summary>
        /// 组织资料查询
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("select")]
        public List<DBMdOrg> select()
        {
            List<DBMdOrg> listdbmdorg = null;
            return listdbmdorg;
        }

     
    }
}

MyDBContext.cs

using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using webapi.Entity;
using webapi.Entity.DBEntity;

namespace webapi.EF
{
    public class MyDBContext : DbContext
    {

        //public MyDBContext(DbContextOptions<MyDBContext> options)
        //    : base(options)
        //{
        //}

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            //注入Sql链接字符串
            optionsBuilder.UseSqlServer(@"Initial Catalog = glx;Data Source = GAOLINXI-PC\MSSQLSERVER1;User ID = sa;Password = 123456");
        }

        public DbSet<MdOrg> mdorg { get; set; }
        public DbSet<DBAPI_IdentityID> identityid { get; set; }

    }
}

MdOrg.cs

using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;
using webapi.MyAttributes;

namespace webapi.Entity
{

    [Table("MdOrg")]
    public class MdOrg
    {
        [Required(ErrorMessage = "id不能为空")]
        public int id { set; get; }

        [Required(AllowEmptyStrings = true)]
        public string orgcode { set; get; }

        [Required(AllowEmptyStrings = true)]
        public string orgname { set; get; }

        [Range(0,2000,ErrorMessage ="大小只能在0~2000之间")]
        public int Year { set; get; }

        [ValueListAttribute(ErrorMessage ="只能是REG1,REG2,REG3")]
        public string valueType { set; get; }

       
        public string nosee { set; get; }


        [NotMapped]
        public List<MdOrgSub1> detailList { set; get; }

    }
}

 

MdOrgSub1.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace webapi.Entity
{
    public class MdOrgSub1
    {

        public int id { set; get; }
        public string subname { set; get; }
    }
}

DBAPI_IdentityID.cs

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;

namespace webapi.Entity.DBEntity
{

    [Table("API_IdentityID")]
    public class DBAPI_IdentityID
    {
        public int ID { set; get; }
        public string IdentityID { set; get; }
        public string IP { set; get; }
        public string UserDesc { set; get; }
        public string Remark { set; get; }
        public Nullable<DateTime> create_date { set; get; }
        public string create_user { set; get; }
        public Nullable<DateTime> update_date { set; get; }
        public string update_user { set; get; }
    }
}

DBMdOrg.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace webapi.Entity.DBEntity
{
    public class DBMdOrg : MdOrg
    {
       
        public string strDB1 { set; get; }
    }
}

ValueListAttribute.cs

说明:自定义的一个特性类,主要是有一些数据上传的时候,只能是list中的值,所以简单的选择了这种方式。

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;

namespace webapi.MyAttributes
{
    public class ValueListAttribute: ValidationAttribute
    {
        public ValueListAttribute()
        {

        }
        public override bool IsValid(object value)
        {
            string[] valuelist ={"REG1", "REG2", "REG3"};
            if (value==null)
            {
                return true;
            }
            if (valuelist.Contains(value.ToString()))
            {
                return true;
            }
            else
            {
                return false;
            }
            
        }
    }
}

 

CheckID.cs

说明:

这里主要是为了验证权限,思路是在数据库中创建一个IdentityID和请求IP对应的关系表,用来判断是否合法,获取请求IP还未完善。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using webapi.EF;
using webapi.Entity;
using webapi.Entity.DBEntity;

namespace webapi.Untils
{
    public class CheckID
    {

        public string chkRights(string strIdentityID,string strIP)
        {
            string strRet = "0";
            MyDBContext _context = new MyDBContext();
            
            List<DBAPI_IdentityID> listret = _context.identityid.Where(tmp=>tmp.IdentityID.Equals(strIdentityID)&& tmp.IP.Equals(strIP)).ToList();
            List<DBAPI_IdentityID> listretID = _context.identityid.Where(tmp => tmp.IdentityID.Equals(strIdentityID) ).ToList();
            if (listret !=null && listret.Count>0)
            {
                strRet = "1";//id和ip一致
                return strRet;
            }
            if (listretID !=null && listretID.Count>=1)
            {
                strRet = "IdentityID对应的IP不存在权限列表中";
                return strRet;
            }
            else
            {
                strRet = "IdentityID不存在,请联系管理员添加";
                return strRet;
            }
            

            
            
        }
    }
}

Program.cs

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;

namespace webapi
{
    public class Program
    {
        public static void Main(string[] args)
        {
            CreateWebHostBuilder(args).Build().Run();
        }

        public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseStartup<Startup>();
    }
}

Startup.cs

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
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.Logging;
using Microsoft.Extensions.Options;
using Microsoft.OpenApi.Models;
using webapi.Untils;

namespace webapi
{
    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.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
            //配置Swagger
            //注册Swagger生成器,定义一个Swagger 文档
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo
                {
                    Version = "v1",
                    Title = "接口文档",
                    Description = "RESTful API"
                });
                // 为 Swagger 设置xml文档注释路径
                var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
                var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
                c.IncludeXmlComments(xmlPath);
            });
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseHsts();
            }
            //启用中间件服务生成Swagger
            app.UseSwagger();
            //启用中间件服务生成SwaggerUI,指定Swagger JSON终结点
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "Web App V1");
                c.RoutePrefix = string.Empty;//设置根节点访问
                c.DefaultModelsExpandDepth(-1);//这里用来设置model类是否显示
            });



            app.UseHttpsRedirection();
            app.UseMvc();
        }
    }


}

 

最终运行的画面

 

觉得比较好的地方是,直接将实体类变成对应的json格式,测试比较方便,后台也不需要进行json到实体类的转换,直接就能操作了。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Netcore6.0是微软推出的全新版本的开发框架,它提供了强大且灵活的功能,用于构建Web应用程序和APIWeb API是Netcore6.0中的一项重要功能,它允许我们构建基于HTTP协议的API,并通过JSON格式进行数据交换。 JWT(JSON Web Token)是一种用于在网络应用间传递信息的安全方法。在Netcore6.0中,我们可以使用JWT来实现Web API的授权功能。JWT由三部分组成:头部、载荷和签名。头部包含了令牌的类型和算法,载荷包含了我们想要传递的数据,签名通过使用密钥进行加密来验证令牌的合法性。 在Netcore6.0中,我们可以使用Microsoft提供的Microsoft.AspNetCore.Authentication.JwtBearer包来简单地实现JWT的授权功能。首先,我们需要在Startup.cs文件的ConfigureServices方法中配置JWT的身份验证服务,并指定密钥、颁发者、验证等参数。然后,在Configure方法中启用身份验证中间件和JWT授权中间件。 在Vue3中,我们可以使用Axios库来发送HTTP请求并附带JWT令牌进行授权。Vue3是一种流行的JavaScript框架,用于构建现代化的用户界面。通过Axios,我们可以将JWT令牌添加到请求的Authorization头部中,并在后端接收到请求时进行验证。 为了实现Vue3与Netcore6.0的JWT授权,我们首先需要在Vue3项目中安装Axios库,并配置请求拦截器,在每个请求发送前将JWT令牌添加到请求头中。后端接收到带有JWT令牌的请求后,使用相同的密钥和算法进行解密并验证令牌的合法性。 综上所述,Netcore6.0的Web API和Vue3的JWT授权组合,可以实现安全可靠的API授权。通过合理的配置和使用,我们可以保护API免受未经授权的访问,并确保只有经过身份验证的用户才能访问敏感数据或执行特定操作。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值