个人做的一个练习,记录一下,只适合新手参考,不正确的地方多多批评指正。
说明的几个点:
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到实体类的转换,直接就能操作了。