Commit dc7e6929 by zxw

init

parents

要显示的修改太多。

为保证性能只显示 1000 of 1000+ 个文件。

**/.classpath
**/.dockerignore
**/.env
**/.git
**/.gitignore
**/.project
**/.settings
**/.toolstarget
**/.vs
**/.vscode
**/*.*proj.user
**/*.dbmdl
**/*.jfm
**/azds.yaml
**/bin
**/charts
**/docker-compose*
**/Dockerfile*
**/node_modules
**/npm-debug.log
**/obj
**/secrets.dev.yaml
**/values.dev.yaml
LICENSE
README.md
\ No newline at end of file
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
# User-specific files
*.suo
*.user
*.sln.docstates
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
build/
bld/
[Bb]in/
[Oo]bj/
# Roslyn cache directories
*.ide/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
#NUNIT
*.VisualState.xml
TestResult.xml
# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c
*_i.c
*_p.c
*_i.h
*.ilk
*.meta
*.obj
*.pch
*.pdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*.log
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc
# Chutzpah Test files
_Chutzpah*
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opensdf
*.sdf
*.cachefile
# Visual Studio profiler
*.psess
*.vsp
*.vspx
# TFS 2012 Local Workspace
$tf/
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# JustCode is a .NET coding addin-in
.JustCode
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# NCrunch
_NCrunch_*
.*crunch*.local.xml
# MightyMoose
*.mm.*
AutoTest.Net/
# Web workbench (sass)
.sass-cache/
# Installshield output folder
[Ee]xpress/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish/
# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
## TODO: Comment the next line if you want to checkin your
## web deploy settings but do note that will include unencrypted
## passwords
*.pubxml
# NuGet Packages
packages/*
*.nupkg
## TODO: If the tool you use requires repositories.config
## uncomment the next line
#!packages/repositories.config
# Enable "build/" folder in the NuGet Packages folder since
# NuGet packages use it for MSBuild targets.
# This line needs to be after the ignore of the build folder
# (and the packages folder if the line above has been uncommented)
!packages/build/
# Windows Azure Build Output
csx/
*.build.csdef
# Windows Store app package directory
AppPackages/
# Others
sql/
*.Cache
ClientBin/
[Ss]tyle[Cc]op.*
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.pfx
*.publishsettings
node_modules/
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
# SQL Server files
*.mdf
*.ldf
# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
# Microsoft Fakes
FakesAssemblies/
/.vs
/JmpModel/CodeTemplates
/JunmpPoliceStation/appsettings.json
/JunmpPoliceStation/internal-nlog.txt
/JunmpPoliceStation/JunmpPoliceStation.xml
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace ApiCommon
{
public class AjaxResult
{
/// <summary>
/// 状态码
/// </summary>
public object state { get; set; }
/// <summary>
/// 返回消息内容
/// </summary>
public string message { get; set; }
/// <summary>
/// 返回数据
/// </summary>
public object data { get; set; }
}
}
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Newtonsoft.Json" Version="12.0.3" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\ApiModel\ApiModel.csproj" />
</ItemGroup>
</Project>
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Text;
namespace ApiCommon
{
public static class ComExtensions
{
/// <summary>
/// 将对象转换层JSON字符串
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="data"></param>
/// <returns></returns>
public static string ToJson<T>(this T data)
{
return JsonConvert.SerializeObject(data);
}
public static bool IsEmpty(this string str)
{
return string.IsNullOrEmpty(str);
}
}
}
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Text;
namespace ApiCommon
{
public static class JsonManager
{
public static AjaxResult SuccessMsg(string msg)
{
return new AjaxResult { data = default, message = msg, state = ResultType.success.ToString() };
}
public static AjaxResult ErrorMsg(string msg)
{
return new AjaxResult { data = default, message = msg, state = ResultType.error.ToString() };
}
public static dynamic CustMsg(string msg, ResultType result)
{
return new { message = msg, state = result };
}
public static dynamic CustMsg<T>(string msg, ResultType result, T data)
{
return new { message = msg, state = result, data = data };
}
}
}
using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text;
namespace ApiCommon
{
public class Md5
{
/// <summary>
/// MD5加密
/// </summary>
/// <param name="str">加密字符</param>
/// <param name="code">加密位数16/32</param>
/// <returns></returns>
public static string md5(string str, int bit)
{
using (MD5CryptoServiceProvider md5Hasher = new MD5CryptoServiceProvider())
{
byte[] hashedDataBytes;
hashedDataBytes = md5Hasher.ComputeHash(Encoding.UTF8.GetBytes(str));
StringBuilder tmp = new StringBuilder();
foreach (byte i in hashedDataBytes)
{
tmp.Append(i.ToString("x2"));
}
if (bit == 16)
return tmp.ToString().Substring(8, 16);
else
if (bit == 32) return tmp.ToString();//默认情况
else return string.Empty;
}
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
namespace ApiCommon
{
/// <summary>
/// 拼接表达式树
/// </summary>
public static class MyLambda
{
//public static Expression<Func<T, bool>> True<T>()
//{
// return f => true;
//}
//public static Expression<Func<T, bool>> False<T>()
//{
// return f => false;
//}
//public static Expression<Func<T, bool>> Or<T>(this Expression<Func<T, bool>> expression1, Expression<Func<T, bool>> expression2)
//{
// var invokedExpression = Expression.Invoke(expression2, expression1.Parameters.Cast<Expression>());
// return Expression.Lambda<Func<T, bool>>(Expression.Or(expression1.Body, invokedExpression), expression1.Parameters);
//}
//public static Expression<Func<T, bool>> And<T>(this Expression<Func<T, bool>> expression1, Expression<Func<T, bool>> expression2)
//{
// var invokedExpression = Expression.Invoke(expression2, expression1.Parameters.Cast<Expression>());
// return Expression.Lambda<Func<T, bool>>(Expression.And(expression1.Body, invokedExpression), expression1.Parameters);
//}
public static Expression<Func<T, bool>> True<T>() { return f => true; }
public static Expression<Func<T, bool>> False<T>() { return f => false; }
public static Expression<T> Compose<T>(this Expression<T> first, Expression<T> second, Func<Expression, Expression, Expression> merge)
{
// build parameter map (from parameters of second to parameters of first)
var map = first.Parameters.Select((f, i) => new { f, s = second.Parameters[i] }).ToDictionary(p => p.s, p => p.f);
// replace parameters in the second lambda expression with parameters from the first
var secondBody = ParameterRebinder.ReplaceParameters(map, second.Body);
// apply composition of lambda expression bodies to parameters from the first expression
return Expression.Lambda<T>(merge(first.Body, secondBody), first.Parameters);
}
public static Expression<Func<T, bool>> And<T>(this Expression<Func<T, bool>> first, Expression<Func<T, bool>> second)
{
return first.Compose(second, Expression.And);
}
public static Expression<Func<T, bool>> AndAlso<T>(this Expression<Func<T, bool>> first, Expression<Func<T, bool>> second)
{
return first.Compose(second, Expression.AndAlso);
}
public static Expression<Func<T, bool>> Or<T>(this Expression<Func<T, bool>> first, Expression<Func<T, bool>> second)
{
return first.Compose(second, Expression.Or);
}
}
public class ParameterRebinder : ExpressionVisitor
{
private readonly Dictionary<ParameterExpression, ParameterExpression> map;
public ParameterRebinder(Dictionary<ParameterExpression, ParameterExpression> map)
{
this.map = map ?? new Dictionary<ParameterExpression, ParameterExpression>();
}
public static Expression ReplaceParameters(Dictionary<ParameterExpression, ParameterExpression> map, Expression exp)
{
return new ParameterRebinder(map).Visit(exp);
}
protected override Expression VisitParameter(ParameterExpression p)
{
ParameterExpression replacement;
if (map.TryGetValue(p, out replacement))
{
p = replacement;
}
return base.VisitParameter(p);
}
}
}
using ApiModel.Basic;
using System;
using System.Collections.Generic;
using System.Text;
namespace ApiCommon
{
public class Pager
{
public static TableMsg Paging<T>(PageData<T> page)
{
return new TableMsg { code = 0, msg = "", count = page.total, data = page.data };
}
public static TableMsg Paging<T>(IList<T> list, long total)
{
return new TableMsg { code = 0, msg = "", count = total, data = list };
}
}
public class TableMsg
{
public int code { get; set; }
public string msg { get; set; }
public long count { get; set; }
public dynamic data { get; set; }
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace ApiCommon
{
public enum ResultType
{
/// <summary>
/// 消息结果类型
/// </summary>
info = 0,
/// <summary>
/// 成功结果类型
/// </summary>
success = 1,
/// <summary>
/// 警告结果类型
/// </summary>
warning = 2,
/// <summary>
/// 异常结果类型
/// </summary>
error = 3,
/// <summary>
/// 无效参数
/// </summary>
invalid_par = 4,
/// <summary>
/// 组织机构未授权
/// </summary>
org_unauthorized = 5,
/// <summary>
/// api未授权
/// </summary>
api_unauthorized = 6,
/// <summary>
/// 未注册
/// </summary>
unregistered = 7,
/// <summary>
/// appkey不存在
/// </summary>
not_extist = 8
}
}
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
namespace ApiCommon
{
public class XmlConvert
{
/// <summary>
/// XML反序列化
/// </summary>
/// <returns></returns>
public static T DeserializeObject<T>(string _xml)
{
try
{
T obj;
using (MemoryStream _ms = new MemoryStream(Encoding.UTF8.GetBytes(_xml)))
{
using (XmlReader _reader = XmlReader.Create(_ms))
{
XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
obj = (T)xmlSerializer.Deserialize(_reader);
}
}
return obj;
}
catch (Exception ex)
{
//Logs.ErrorLog(ex.ToString(), MethodBase.GetCurrentMethod().Name);
return default;
}
}
/// <summary>
/// XML反序列化
/// </summary>
/// <returns></returns>
public static T DeserializeObject<T>(byte[] buffer)
{
try
{
T obj;
using (MemoryStream _ms = new MemoryStream(buffer))
{
using (XmlReader _reader = XmlReader.Create(_ms))
{
XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
obj = (T)xmlSerializer.Deserialize(_reader);
}
}
return obj;
}
catch (Exception ex)
{
//Logs.ErrorLog(ex.ToString(), MethodBase.GetCurrentMethod().Name);
return default;
}
}
/// <summary>
/// XML序列化
/// </summary>
/// <param name="strobj"></param>
private static string SerializeObject<T>(T obj)
{
try
{
var _namespace = new XmlSerializerNamespaces();
_namespace.Add(string.Empty, string.Empty);
XmlSerializer serializer = new XmlSerializer(obj.GetType());
var _xmlSetting = new XmlWriterSettings
{
Encoding = Encoding.UTF8,
Indent = false,
OmitXmlDeclaration = true,
NewLineHandling = NewLineHandling.Replace,
};
using (StringWriter _writer = new Utf8StringWriter())
{
using (var _xmlWriter = XmlWriter.Create(_writer, _xmlSetting))
{
serializer.Serialize(_xmlWriter, obj, _namespace);
return _writer.ToString();
}
}
}
catch (Exception ex)
{
return string.Empty;
}
}
public class Utf8StringWriter : StringWriter
{
public override Encoding Encoding
{
get
{
return Encoding.UTF8;
}
}
}
}
}
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="3.1.10" />
<PackageReference Include="Newtonsoft.Json" Version="12.0.3" />
</ItemGroup>
</Project>
using System;
using System.Collections.Generic;
using System.Text;
namespace ApiModel.Basic
{
public class PageData<T>
{
public IList<T> data { get; set; }
public long total { get; set; }
}
}
using ApiModel.Entity;
using ApiModel.Repository;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Storage;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ApiModel.Basic
{
public class UnitOfWork : IDisposable
{
public ApiSysContext DbContext { get; set; } = default;
public UnitOfWork(ApiSysContext dbContext)
{
DbContext = dbContext;
}
#region 字段
public ApiMqttMessageRepository _ApiMqttMessageRepository = default;
public ApiOrgRepository _ApiOrgRepository = default;
private ApiSrcRepository _ApiSrcRepository = default;
private SysButtonRepository _SysButtonRepository = default;
private SysModuleRepository _SysModuleRepository = default;
private SysAppApiRepository _SysAppApiRepository = default;
private SysRoleAuthRepository _SysRoleAuthRepository = default;
private SysRoleRepository _SysRoleRepository = default;
private SysUserApiOrgRepository _SysUserApiOrgRepository = default;
private SysUserRepository _SysUserRepository = default;
private SysOrgRepository _SysOrgRepository = default;
private SysAppsTypeRepository _SysAppsTypeRepository = default;
private SysAppsRepository _SysAppsRepository = default;
private SysAppTypeApiRepository _SysAppTypeApiRepository = default;
private VAppApiRepository _VAppApiRepository = default;
private SysLoginlogRepository _SysLoginlogRepository = default;
#endregion
#region 操作类属性
public ApiMqttMessageRepository ApiDevicePushLogRepository => _ApiMqttMessageRepository ?? (_ApiMqttMessageRepository = new ApiMqttMessageRepository(DbContext));
public SysLoginlogRepository SysLoginlogRepository => _SysLoginlogRepository ?? (_SysLoginlogRepository = new SysLoginlogRepository(DbContext));
public VAppApiRepository VAppApiRepository => _VAppApiRepository ?? (_VAppApiRepository = new VAppApiRepository(DbContext));
public SysAppsRepository SysAppsRepository => _SysAppsRepository ?? (_SysAppsRepository = new SysAppsRepository(DbContext));
public SysAppsTypeRepository SysAppsTypeRepository => _SysAppsTypeRepository ?? (_SysAppsTypeRepository = new SysAppsTypeRepository(DbContext));
public SysOrgRepository SysOrgRepository => _SysOrgRepository ?? (_SysOrgRepository = new SysOrgRepository(DbContext));
public ApiOrgRepository ApiOrgRepository => _ApiOrgRepository ?? (_ApiOrgRepository = new ApiOrgRepository(DbContext));
public ApiSrcRepository ApiSrcRepository => _ApiSrcRepository ?? (_ApiSrcRepository = new ApiSrcRepository(DbContext));
public SysButtonRepository SysButtonRepository => _SysButtonRepository ?? (_SysButtonRepository = new SysButtonRepository(DbContext));
public SysModuleRepository SysModuleRepository => _SysModuleRepository ?? (_SysModuleRepository = new SysModuleRepository(DbContext));
public SysAppApiRepository SysAppApiRepository => _SysAppApiRepository ?? (_SysAppApiRepository = new SysAppApiRepository(DbContext));
public SysAppTypeApiRepository SysAppTypeApiRepository => _SysAppTypeApiRepository ?? (_SysAppTypeApiRepository = new SysAppTypeApiRepository(DbContext));
public SysRoleAuthRepository SysRoleAuthRepository => _SysRoleAuthRepository ?? (_SysRoleAuthRepository = new SysRoleAuthRepository(DbContext));
public SysRoleRepository SysRoleRepository => _SysRoleRepository ?? (_SysRoleRepository = new SysRoleRepository(DbContext));
public SysUserApiOrgRepository SysUserApiOrgRepository => _SysUserApiOrgRepository ?? (_SysUserApiOrgRepository = new SysUserApiOrgRepository(DbContext));
public SysUserRepository SysUserRepository => _SysUserRepository ?? (_SysUserRepository = new SysUserRepository(DbContext));
#endregion
#region 仓储操作(提交事务保存SaveChanges(),回滚RollBackChanges(),释放资源Dispose()
/// <summary>
/// 保存
/// </summary>
public int SaveChanges()
{
return DbContext.SaveChanges();
}
public async Task<int> SaveChangesAsync()
{
return await DbContext.SaveChangesAsync();
}
/// <summary>
/// 回滚
/// </summary>
public void RollBackChanges()
{
var items = DbContext.ChangeTracker.Entries().ToList();
items.ForEach(o => o.State = EntityState.Unchanged);
}
/// <summary>
/// 释放资源
/// </summary>
private bool disposed = false;
protected virtual void Dispose(bool disposing)
{
if (!this.disposed)
{
if (disposing)
{
DbContext.Dispose();//随着工作单元的销毁而销毁
}
}
this.disposed = true;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
public IDbContextTransaction BeginTransaction()
{
var scope = DbContext.Database.BeginTransaction();
return scope;
}
#endregion
}
}
// <auto-generated> This file has been auto generated by EF Core Power Tools. </auto-generated>
#nullable disable
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace ApiModel.Entity
{
[Table("api_mqtt_message")]
public partial class ApiMqttMessage
{
[Key]
[Column("id")]
[StringLength(36)]
public string Id { get; set; }
[Column("createTime", TypeName = "datetime")]
public DateTime? CreateTime { get; set; }
/// <summary>
/// 设备类型
/// </summary>
[Column("deviceType")]
[StringLength(255)]
public string DeviceType { get; set; }
/// <summary>
/// 设备编号
/// </summary>
[Column("deviceNo")]
[StringLength(255)]
public string DeviceNo { get; set; }
/// <summary>
/// 标题
/// </summary>
[Column("topic")]
[StringLength(255)]
public string Topic { get; set; }
/// <summary>
/// 内容
/// </summary>
[Column("payload", TypeName = "text")]
public string Payload { get; set; }
}
}
\ No newline at end of file
// <auto-generated> This file has been auto generated by EF Core Power Tools. </auto-generated>
#nullable disable
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace ApiModel.Entity
{
[Table("api_org")]
public partial class ApiOrg
{
public ApiOrg()
{
SysUserApiOrgs = new HashSet<SysUserApiOrg>();
}
[Key]
[Column("id")]
[StringLength(36)]
public string Id { get; set; }
[Column("name")]
[StringLength(200)]
public string Name { get; set; }
[Column("createTime", TypeName = "datetime")]
public DateTime? CreateTime { get; set; }
[Column("sort_code")]
public int SortCode { get; set; }
[Column("code")]
[StringLength(20)]
public string Code { get; set; }
[Column("area_name")]
[StringLength(50)]
public string AreaName { get; set; }
[Column("parent_id")]
[StringLength(36)]
public string ParentId { get; set; }
[Column("state")]
public int? State { get; set; }
[InverseProperty(nameof(SysUserApiOrg.Org))]
public virtual ICollection<SysUserApiOrg> SysUserApiOrgs { get; set; }
}
}
\ No newline at end of file
// <auto-generated> This file has been auto generated by EF Core Power Tools. </auto-generated>
#nullable disable
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace ApiModel.Entity
{
[Table("api_src")]
public partial class ApiSrc
{
[Key]
[Column("id")]
[StringLength(36)]
public string Id { get; set; }
[Column("name")]
public string Name { get; set; }
[Column("url")]
public string Url { get; set; }
[Column("createTime", TypeName = "datetime")]
public DateTime? CreateTime { get; set; }
[Column("isdel")]
public bool? Isdel { get; set; }
[Column("demo_text")]
public string DemoText { get; set; }
[Column("type")]
[StringLength(20)]
public string Type { get; set; }
[Column("sort_code")]
public int SortCode { get; set; }
[Column("needOrg")]
public bool? NeedOrg { get; set; }
}
}
\ No newline at end of file
// <auto-generated> This file has been auto generated by EF Core Power Tools. </auto-generated>
#nullable disable
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata;
namespace ApiModel.Entity
{
public partial class ApiSysContext : DbContext
{
public ApiSysContext()
{
}
public ApiSysContext(DbContextOptions<ApiSysContext> options)
: base(options)
{
}
public virtual DbSet<ApiMqttMessage> ApiMqttMessages { get; set; }
public virtual DbSet<ApiOrg> ApiOrgs { get; set; }
public virtual DbSet<ApiSrc> ApiSrcs { get; set; }
public virtual DbSet<SysApp> SysApps { get; set; }
public virtual DbSet<SysAppApi> SysAppApis { get; set; }
public virtual DbSet<SysAppsType> SysAppsTypes { get; set; }
public virtual DbSet<SysApptypeApi> SysApptypeApis { get; set; }
public virtual DbSet<SysButton> SysButtons { get; set; }
public virtual DbSet<SysLoginlog> SysLoginlogs { get; set; }
public virtual DbSet<SysModule> SysModules { get; set; }
public virtual DbSet<SysOrg> SysOrgs { get; set; }
public virtual DbSet<SysRole> SysRoles { get; set; }
public virtual DbSet<SysRoleAuth> SysRoleAuths { get; set; }
public virtual DbSet<SysUser> SysUsers { get; set; }
public virtual DbSet<SysUserApiOrg> SysUserApiOrgs { get; set; }
public virtual DbSet<VAppApi> VAppApis { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<ApiMqttMessage>(entity =>
{
entity.Property(e => e.Id).IsUnicode(false);
entity.Property(e => e.CreateTime).HasDefaultValueSql("(getdate())");
entity.Property(e => e.DeviceNo).HasComment("设备编号");
entity.Property(e => e.DeviceType).HasComment("设备类型");
entity.Property(e => e.Payload).HasComment("内容");
entity.Property(e => e.Topic).HasComment("标题");
});
modelBuilder.Entity<ApiOrg>(entity =>
{
entity.Property(e => e.Id).IsUnicode(false);
entity.Property(e => e.ParentId).IsUnicode(false);
entity.Property(e => e.State).HasDefaultValueSql("((1))");
});
modelBuilder.Entity<ApiSrc>(entity =>
{
entity.Property(e => e.Id).IsUnicode(false);
});
modelBuilder.Entity<SysApp>(entity =>
{
entity.Property(e => e.Id).IsUnicode(false);
entity.Property(e => e.AppType).IsUnicode(false);
entity.Property(e => e.UserId).IsUnicode(false);
entity.HasOne(d => d.AppTypeNavigation)
.WithMany(p => p.SysApps)
.HasForeignKey(d => d.AppType)
.OnDelete(DeleteBehavior.SetNull)
.HasConstraintName("FK_sys_apps_sys_apps_type");
entity.HasOne(d => d.User)
.WithMany(p => p.SysApps)
.HasForeignKey(d => d.UserId)
.OnDelete(DeleteBehavior.SetNull)
.HasConstraintName("FK_sys_apps_sys_user");
});
modelBuilder.Entity<SysAppApi>(entity =>
{
entity.Property(e => e.Id).IsUnicode(false);
entity.Property(e => e.ApiId).IsUnicode(false);
entity.Property(e => e.AppId).IsUnicode(false);
});
modelBuilder.Entity<SysAppsType>(entity =>
{
entity.Property(e => e.Id).IsUnicode(false);
entity.Property(e => e.LimitUserId)
.IsUnicode(false)
.HasComment("限定使用用户id(为空为全部可用)");
});
modelBuilder.Entity<SysApptypeApi>(entity =>
{
entity.Property(e => e.Id).IsUnicode(false);
entity.Property(e => e.ApiId).IsUnicode(false);
entity.Property(e => e.TypeId).IsUnicode(false);
});
modelBuilder.Entity<SysButton>(entity =>
{
entity.Property(e => e.Id).IsUnicode(false);
});
modelBuilder.Entity<SysLoginlog>(entity =>
{
entity.Property(e => e.Id).IsUnicode(false);
});
modelBuilder.Entity<SysModule>(entity =>
{
entity.Property(e => e.Id).IsUnicode(false);
entity.Property(e => e.ParentId).IsUnicode(false);
});
modelBuilder.Entity<SysOrg>(entity =>
{
entity.Property(e => e.Id).IsUnicode(false);
entity.Property(e => e.ParentId).IsUnicode(false);
});
modelBuilder.Entity<SysRole>(entity =>
{
entity.Property(e => e.Id).IsUnicode(false);
});
modelBuilder.Entity<SysRoleAuth>(entity =>
{
entity.Property(e => e.Id).IsUnicode(false);
entity.Property(e => e.ButtonId).IsUnicode(false);
entity.Property(e => e.ModuleId).IsUnicode(false);
entity.Property(e => e.RoleId).IsUnicode(false);
entity.HasOne(d => d.Button)
.WithMany(p => p.SysRoleAuths)
.HasForeignKey(d => d.ButtonId)
.HasConstraintName("FK_tb_role_auth_tb_button");
entity.HasOne(d => d.Module)
.WithMany(p => p.SysRoleAuths)
.HasForeignKey(d => d.ModuleId)
.HasConstraintName("FK_tb_role_auth_tb_module");
entity.HasOne(d => d.Role)
.WithMany(p => p.SysRoleAuths)
.HasForeignKey(d => d.RoleId)
.HasConstraintName("FK_tb_role_auth_tb_role");
});
modelBuilder.Entity<SysUser>(entity =>
{
entity.Property(e => e.Id).IsUnicode(false);
entity.Property(e => e.Certificate).HasComment("公司营业执照照片");
entity.Property(e => e.CreateTime).HasComment("创建时间");
entity.Property(e => e.CreditCode).HasComment("统一社会信用代码");
entity.Property(e => e.DeptId).IsUnicode(false);
entity.Property(e => e.HeadIcon).HasComment("头像地址");
entity.Property(e => e.IsApprove).HasDefaultValueSql("((0))");
entity.Property(e => e.Isdel).HasComment("是否删除");
entity.Property(e => e.Password).HasComment("登录密码");
entity.Property(e => e.RoleId).IsUnicode(false);
entity.Property(e => e.SortCode).HasComment("排序码");
entity.HasOne(d => d.Dept)
.WithMany(p => p.SysUsers)
.HasForeignKey(d => d.DeptId)
.OnDelete(DeleteBehavior.SetNull)
.HasConstraintName("FK_sys_user_sys_org");
entity.HasOne(d => d.Role)
.WithMany(p => p.SysUsers)
.HasForeignKey(d => d.RoleId)
.OnDelete(DeleteBehavior.SetNull)
.HasConstraintName("FK_sys_user_sys_role");
});
modelBuilder.Entity<SysUserApiOrg>(entity =>
{
entity.Property(e => e.Id).IsUnicode(false);
entity.Property(e => e.OrgId).IsUnicode(false);
entity.Property(e => e.UserId).IsUnicode(false);
entity.HasOne(d => d.Org)
.WithMany(p => p.SysUserApiOrgs)
.HasForeignKey(d => d.OrgId)
.HasConstraintName("FK_tb_user_api_org_tb_api_org");
entity.HasOne(d => d.User)
.WithMany(p => p.SysUserApiOrgs)
.HasForeignKey(d => d.UserId)
.OnDelete(DeleteBehavior.SetNull)
.HasConstraintName("FK_tb_user_api_org_tb_user");
});
modelBuilder.Entity<VAppApi>(entity =>
{
entity.HasNoKey();
entity.ToView("v_app_api");
entity.Property(e => e.ApiId).IsUnicode(false);
entity.Property(e => e.AppType).IsUnicode(false);
entity.Property(e => e.Id).IsUnicode(false);
entity.Property(e => e.UserId).IsUnicode(false);
});
OnModelCreatingPartial(modelBuilder);
}
partial void OnModelCreatingPartial(ModelBuilder modelBuilder);
}
}
\ No newline at end of file
// <auto-generated> This file has been auto generated by EF Core Power Tools. </auto-generated>
#nullable disable
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace ApiModel.Entity
{
[Table("sys_apps")]
public partial class SysApp
{
[Key]
[Column("id")]
[StringLength(36)]
public string Id { get; set; }
[Column("name")]
public string Name { get; set; }
[Column("description")]
public string Description { get; set; }
[Column("create_time", TypeName = "datetime")]
public DateTime? CreateTime { get; set; }
[Column("sort_code")]
public int SortCode { get; set; }
[Column("app_type")]
[StringLength(36)]
public string AppType { get; set; }
[Column("appkey")]
public string Appkey { get; set; }
[Column("secret_key")]
public string SecretKey { get; set; }
[Column("user_id")]
[StringLength(36)]
public string UserId { get; set; }
[ForeignKey(nameof(AppType))]
[InverseProperty(nameof(SysAppsType.SysApps))]
public virtual SysAppsType AppTypeNavigation { get; set; }
[ForeignKey(nameof(UserId))]
[InverseProperty(nameof(SysUser.SysApps))]
public virtual SysUser User { get; set; }
}
}
\ No newline at end of file
// <auto-generated> This file has been auto generated by EF Core Power Tools. </auto-generated>
#nullable disable
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace ApiModel.Entity
{
[Table("sys_app_api")]
public partial class SysAppApi
{
[Key]
[Column("id")]
[StringLength(36)]
public string Id { get; set; }
[Column("app_id")]
[StringLength(36)]
public string AppId { get; set; }
[Column("api_id")]
[StringLength(36)]
public string ApiId { get; set; }
}
}
\ No newline at end of file
// <auto-generated> This file has been auto generated by EF Core Power Tools. </auto-generated>
#nullable disable
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace ApiModel.Entity
{
[Table("sys_apps_type")]
public partial class SysAppsType
{
public SysAppsType()
{
SysApps = new HashSet<SysApp>();
}
[Key]
[Column("id")]
[StringLength(36)]
public string Id { get; set; }
[Column("name")]
public string Name { get; set; }
[Column("description")]
public string Description { get; set; }
[Column("create_time", TypeName = "datetime")]
public DateTime? CreateTime { get; set; }
[Column("sort_code")]
public int SortCode { get; set; }
/// <summary>
/// 限定使用用户id(为空为全部可用)
/// </summary>
[Column("limit_user_id")]
[StringLength(36)]
public string LimitUserId { get; set; }
[InverseProperty(nameof(SysApp.AppTypeNavigation))]
public virtual ICollection<SysApp> SysApps { get; set; }
}
}
\ No newline at end of file
// <auto-generated> This file has been auto generated by EF Core Power Tools. </auto-generated>
#nullable disable
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace ApiModel.Entity
{
[Table("sys_apptype_api")]
public partial class SysApptypeApi
{
[Key]
[Column("id")]
[StringLength(36)]
public string Id { get; set; }
[Column("type_id")]
[StringLength(36)]
public string TypeId { get; set; }
[Column("api_id")]
[StringLength(36)]
public string ApiId { get; set; }
}
}
\ No newline at end of file
// <auto-generated> This file has been auto generated by EF Core Power Tools. </auto-generated>
#nullable disable
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace ApiModel.Entity
{
[Table("sys_button")]
public partial class SysButton
{
public SysButton()
{
SysRoleAuths = new HashSet<SysRoleAuth>();
}
[Key]
[Column("id")]
[StringLength(36)]
public string Id { get; set; }
[Column("code")]
public string Code { get; set; }
[Column("name")]
public string Name { get; set; }
[Column("location")]
public int? Location { get; set; }
[Column("className")]
public string ClassName { get; set; }
[Column("icon")]
public string Icon { get; set; }
[Column("createTime", TypeName = "datetime")]
public DateTime? CreateTime { get; set; }
[Column("sortCode")]
public int? SortCode { get; set; }
[InverseProperty(nameof(SysRoleAuth.Button))]
public virtual ICollection<SysRoleAuth> SysRoleAuths { get; set; }
}
}
\ No newline at end of file
// <auto-generated> This file has been auto generated by EF Core Power Tools. </auto-generated>
#nullable disable
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace ApiModel.Entity
{
[Table("sys_loginlog")]
public partial class SysLoginlog
{
[Key]
[Column("id")]
[StringLength(36)]
public string Id { get; set; }
[Column("account")]
[StringLength(100)]
public string Account { get; set; }
[Column("user_name")]
[StringLength(100)]
public string UserName { get; set; }
[Column("reason")]
[StringLength(100)]
public string Reason { get; set; }
[Column("status")]
[StringLength(100)]
public string Status { get; set; }
[Column("create_time", TypeName = "datetime")]
public DateTime? CreateTime { get; set; }
[Column("ip_address")]
[StringLength(50)]
public string IpAddress { get; set; }
}
}
\ No newline at end of file
// <auto-generated> This file has been auto generated by EF Core Power Tools. </auto-generated>
#nullable disable
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace ApiModel.Entity
{
[Table("sys_module")]
public partial class SysModule
{
public SysModule()
{
SysRoleAuths = new HashSet<SysRoleAuth>();
}
[Key]
[Column("id")]
[StringLength(36)]
public string Id { get; set; }
[StringLength(36)]
public string ParentId { get; set; }
public string Name { get; set; }
public string FontFamily { get; set; }
public string Icon { get; set; }
public string UrlAddress { get; set; }
public int? SortCode { get; set; }
[Column(TypeName = "datetime")]
public DateTime? CreateTime { get; set; }
[InverseProperty(nameof(SysRoleAuth.Module))]
public virtual ICollection<SysRoleAuth> SysRoleAuths { get; set; }
}
}
\ No newline at end of file
// <auto-generated> This file has been auto generated by EF Core Power Tools. </auto-generated>
#nullable disable
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace ApiModel.Entity
{
[Table("sys_org")]
public partial class SysOrg
{
public SysOrg()
{
SysUsers = new HashSet<SysUser>();
}
[Key]
[Column("id")]
[StringLength(36)]
public string Id { get; set; }
[StringLength(36)]
public string ParentId { get; set; }
[StringLength(100)]
public string Code { get; set; }
[StringLength(100)]
public string Name { get; set; }
public int? SortCode { get; set; }
[Column("createTime", TypeName = "datetime")]
public DateTime? CreateTime { get; set; }
[Column("org_type")]
[StringLength(50)]
public string OrgType { get; set; }
[InverseProperty(nameof(SysUser.Dept))]
public virtual ICollection<SysUser> SysUsers { get; set; }
}
}
\ No newline at end of file
// <auto-generated> This file has been auto generated by EF Core Power Tools. </auto-generated>
#nullable disable
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace ApiModel.Entity
{
[Table("sys_role")]
public partial class SysRole
{
public SysRole()
{
SysRoleAuths = new HashSet<SysRoleAuth>();
SysUsers = new HashSet<SysUser>();
}
[Key]
[Column("id")]
[StringLength(36)]
public string Id { get; set; }
[Column("name")]
public string Name { get; set; }
[Column("code")]
public string Code { get; set; }
[Column("sortCode")]
public int? SortCode { get; set; }
[Column("createTime", TypeName = "datetime")]
public DateTime? CreateTime { get; set; }
[InverseProperty(nameof(SysRoleAuth.Role))]
public virtual ICollection<SysRoleAuth> SysRoleAuths { get; set; }
[InverseProperty(nameof(SysUser.Role))]
public virtual ICollection<SysUser> SysUsers { get; set; }
}
}
\ No newline at end of file
// <auto-generated> This file has been auto generated by EF Core Power Tools. </auto-generated>
#nullable disable
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace ApiModel.Entity
{
[Table("sys_role_auth")]
public partial class SysRoleAuth
{
[Key]
[Column("id")]
[StringLength(36)]
public string Id { get; set; }
[Column("button_id")]
[StringLength(36)]
public string ButtonId { get; set; }
[Column("module_id")]
[StringLength(36)]
public string ModuleId { get; set; }
[Column("role_id")]
[StringLength(36)]
public string RoleId { get; set; }
[ForeignKey(nameof(ButtonId))]
[InverseProperty(nameof(SysButton.SysRoleAuths))]
public virtual SysButton Button { get; set; }
[ForeignKey(nameof(ModuleId))]
[InverseProperty(nameof(SysModule.SysRoleAuths))]
public virtual SysModule Module { get; set; }
[ForeignKey(nameof(RoleId))]
[InverseProperty(nameof(SysRole.SysRoleAuths))]
public virtual SysRole Role { get; set; }
}
}
\ No newline at end of file
// <auto-generated> This file has been auto generated by EF Core Power Tools. </auto-generated>
#nullable disable
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace ApiModel.Entity
{
[Table("sys_user")]
public partial class SysUser
{
public SysUser()
{
SysApps = new HashSet<SysApp>();
SysUserApiOrgs = new HashSet<SysUserApiOrg>();
}
[Key]
[Column("id")]
[StringLength(36)]
public string Id { get; set; }
[Column("name")]
public string Name { get; set; }
[Column("sex")]
public bool? Sex { get; set; }
[Column("birthday", TypeName = "datetime")]
public DateTime? Birthday { get; set; }
[Column("account")]
public string Account { get; set; }
/// <summary>
/// 登录密码
/// </summary>
[Column("password")]
public string Password { get; set; }
/// <summary>
/// 创建时间
/// </summary>
[Column("createTime", TypeName = "datetime")]
public DateTime? CreateTime { get; set; }
/// <summary>
/// 排序码
/// </summary>
[Column("sortCode")]
public int? SortCode { get; set; }
/// <summary>
/// 头像地址
/// </summary>
[Column("headIcon")]
public string HeadIcon { get; set; }
[Column("email")]
public string Email { get; set; }
/// <summary>
/// 是否删除
/// </summary>
[Column("isdel")]
public bool? Isdel { get; set; }
/// <summary>
/// 公司营业执照照片
/// </summary>
[Column("certificate")]
public string Certificate { get; set; }
/// <summary>
/// 统一社会信用代码
/// </summary>
[Column("credit_code")]
public string CreditCode { get; set; }
[Column("role_id")]
[StringLength(36)]
public string RoleId { get; set; }
[Column("dept_id")]
[StringLength(36)]
public string DeptId { get; set; }
[Column("is_lock")]
public bool? IsLock { get; set; }
[Column("contact")]
public string Contact { get; set; }
[Column("is_approve")]
[StringLength(20)]
public string IsApprove { get; set; }
[Column("approve_time", TypeName = "datetime")]
public DateTime? ApproveTime { get; set; }
[Column("approve_text")]
public string ApproveText { get; set; }
[Column("letter")]
public string Letter { get; set; }
[Column("contract")]
public string Contract { get; set; }
[ForeignKey(nameof(DeptId))]
[InverseProperty(nameof(SysOrg.SysUsers))]
public virtual SysOrg Dept { get; set; }
[ForeignKey(nameof(RoleId))]
[InverseProperty(nameof(SysRole.SysUsers))]
public virtual SysRole Role { get; set; }
[InverseProperty(nameof(SysApp.User))]
public virtual ICollection<SysApp> SysApps { get; set; }
[InverseProperty(nameof(SysUserApiOrg.User))]
public virtual ICollection<SysUserApiOrg> SysUserApiOrgs { get; set; }
}
}
\ No newline at end of file
// <auto-generated> This file has been auto generated by EF Core Power Tools. </auto-generated>
#nullable disable
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace ApiModel.Entity
{
[Table("sys_user_api_org")]
public partial class SysUserApiOrg
{
[Key]
[Column("id")]
[StringLength(36)]
public string Id { get; set; }
[Column("user_id")]
[StringLength(36)]
public string UserId { get; set; }
[Column("org_id")]
[StringLength(36)]
public string OrgId { get; set; }
[ForeignKey(nameof(OrgId))]
[InverseProperty(nameof(ApiOrg.SysUserApiOrgs))]
public virtual ApiOrg Org { get; set; }
[ForeignKey(nameof(UserId))]
[InverseProperty(nameof(SysUser.SysUserApiOrgs))]
public virtual SysUser User { get; set; }
}
}
\ No newline at end of file
// <auto-generated> This file has been auto generated by EF Core Power Tools. </auto-generated>
#nullable disable
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace ApiModel.Entity
{
public partial class VAppApi
{
[Column("app_type")]
[StringLength(36)]
public string AppType { get; set; }
[Column("secret_key")]
public string SecretKey { get; set; }
[Column("appkey")]
public string Appkey { get; set; }
[Column("name")]
public string Name { get; set; }
[Column("url")]
public string Url { get; set; }
[Column("type")]
[StringLength(20)]
public string Type { get; set; }
[Column("createTime", TypeName = "datetime")]
public DateTime? CreateTime { get; set; }
[Column("user_id")]
[StringLength(36)]
public string UserId { get; set; }
[Required]
[Column("api_id")]
[StringLength(36)]
public string ApiId { get; set; }
[Required]
[Column("id")]
[StringLength(36)]
public string Id { get; set; }
}
}
\ No newline at end of file
using ApiModel.Basic;
using ApiModel.Entity;
using System;
using System.Collections.Generic;
using System.Text;
namespace ApiModel.Repository
{
public class ApiMqttMessageRepository : BaseRepository<ApiMqttMessage>
{
public ApiMqttMessageRepository(ApiSysContext context) : base(context)
{
}
}
}
using ApiModel.Basic;
using ApiModel.Entity;
using System;
using System.Collections.Generic;
using System.Text;
namespace ApiModel.Repository
{
public class ApiOrgRepository : BaseRepository<ApiOrg>
{
public ApiOrgRepository(ApiSysContext context) : base(context)
{
}
}
}
using ApiModel.Basic;
using ApiModel.Entity;
using System;
using System.Collections.Generic;
using System.Text;
namespace ApiModel.Repository
{
public class ApiSrcRepository : BaseRepository<ApiSrc>
{
public ApiSrcRepository(ApiSysContext context) : base(context)
{
}
}
}
using ApiModel.Basic;
using ApiModel.Entity;
using System;
using System.Collections.Generic;
using System.Text;
namespace ApiModel.Repository
{
public class SysAppApiRepository : BaseRepository<SysAppApi>
{
public SysAppApiRepository(ApiSysContext context) : base(context)
{
}
}
}
using ApiModel.Basic;
using ApiModel.Entity;
using System;
using System.Collections.Generic;
using System.Text;
namespace ApiModel.Repository
{
public class SysAppTypeApiRepository : BaseRepository<SysApptypeApi>
{
public SysAppTypeApiRepository(ApiSysContext context) : base(context)
{
}
}
}
using ApiModel.Basic;
using ApiModel.Entity;
using System;
using System.Collections.Generic;
using System.Text;
namespace ApiModel.Repository
{
public class SysAppsRepository : BaseRepository<SysApp>
{
public SysAppsRepository(ApiSysContext context) : base(context)
{
}
}
}
using ApiModel.Basic;
using ApiModel.Entity;
using System;
using System.Collections.Generic;
using System.Text;
namespace ApiModel.Repository
{
public class SysAppsTypeRepository : BaseRepository<SysAppsType>
{
public SysAppsTypeRepository(ApiSysContext context) : base(context)
{
}
}
}
using ApiModel.Basic;
using ApiModel.Entity;
using System;
using System.Collections.Generic;
using System.Text;
namespace ApiModel.Repository
{
public class SysButtonRepository : BaseRepository<SysButton>
{
public SysButtonRepository(ApiSysContext context) : base(context)
{
}
}
}
using ApiModel.Basic;
using ApiModel.Entity;
using System;
using System.Collections.Generic;
using System.Text;
namespace ApiModel.Repository
{
public class SysLoginlogRepository : BaseRepository<SysLoginlog>
{
public SysLoginlogRepository(ApiSysContext context) : base(context)
{
}
}
}
using ApiModel.Basic;
using ApiModel.Entity;
using System;
using System.Collections.Generic;
using System.Text;
namespace ApiModel.Repository
{
public class SysModuleRepository : BaseRepository<SysModule>
{
public SysModuleRepository(ApiSysContext context) : base(context)
{
}
}
}
using ApiModel.Basic;
using ApiModel.Entity;
using System;
using System.Collections.Generic;
using System.Text;
namespace ApiModel.Repository
{
public class SysOrgRepository : BaseRepository<SysOrg>
{
public SysOrgRepository(ApiSysContext context) : base(context)
{
}
}
}
using ApiModel.Basic;
using ApiModel.Entity;
using System;
using System.Collections.Generic;
using System.Text;
namespace ApiModel.Repository
{
public class SysRoleAuthRepository : BaseRepository<SysRoleAuth>
{
public SysRoleAuthRepository(ApiSysContext context) : base(context)
{
}
}
}
using ApiModel.Basic;
using ApiModel.Entity;
using System;
using System.Collections.Generic;
using System.Text;
namespace ApiModel.Repository
{
public class SysRoleRepository : BaseRepository<SysRole>
{
public SysRoleRepository(ApiSysContext context) : base(context)
{
}
}
}
using ApiModel.Basic;
using ApiModel.Entity;
using System;
using System.Collections.Generic;
using System.Text;
namespace ApiModel.Repository
{
public class SysUserApiOrgRepository : BaseRepository<SysUserApiOrg>
{
public SysUserApiOrgRepository(ApiSysContext context) : base(context)
{
}
}
}
using ApiModel.Basic;
using ApiModel.Entity;
using System;
using System.Collections.Generic;
using System.Text;
namespace ApiModel.Repository
{
public class SysUserRepository : BaseRepository<SysUser>
{
public SysUserRepository(ApiSysContext context) : base(context)
{
}
}
}
using ApiModel.Basic;
using ApiModel.Entity;
using System;
using System.Collections.Generic;
using System.Text;
namespace ApiModel.Repository
{
public class VAppApiRepository : BaseRepository<VAppApi>
{
public VAppApiRepository(ApiSysContext context) : base(context)
{
}
}
}
{
"CodeGenerationMode": 1,
"ContextClassName": "ApiSysContext",
"ContextNamespace": null,
"DefaultDacpacSchema": null,
"FilterSchemas": false,
"IncludeConnectionString": false,
"ModelNamespace": null,
"OutputContextPath": null,
"OutputPath": "Entity",
"ProjectRootNamespace": "ApiModel",
"Schemas": null,
"SelectedHandlebarsLanguage": 0,
"SelectedToBeGenerated": 0,
"Tables": [
{
"Name": "[dbo].[api_mqtt_message]",
"ObjectType": 0
},
{
"Name": "[dbo].[api_org]",
"ObjectType": 0
},
{
"Name": "[dbo].[api_src]",
"ObjectType": 0
},
{
"Name": "[dbo].[sys_app_api]",
"ObjectType": 0
},
{
"Name": "[dbo].[sys_apps]",
"ObjectType": 0
},
{
"Name": "[dbo].[sys_apps_type]",
"ObjectType": 0
},
{
"Name": "[dbo].[sys_apptype_api]",
"ObjectType": 0
},
{
"Name": "[dbo].[sys_button]",
"ObjectType": 0
},
{
"Name": "[dbo].[sys_loginlog]",
"ObjectType": 0
},
{
"Name": "[dbo].[sys_module]",
"ObjectType": 0
},
{
"Name": "[dbo].[sys_org]",
"ObjectType": 0
},
{
"Name": "[dbo].[sys_role]",
"ObjectType": 0
},
{
"Name": "[dbo].[sys_role_auth]",
"ObjectType": 0
},
{
"Name": "[dbo].[sys_user]",
"ObjectType": 0
},
{
"Name": "[dbo].[sys_user_api_org]",
"ObjectType": 0
},
{
"Name": "[dbo].[v_app_api]",
"ObjectType": 3
}
],
"UiHint": "PC.ApiSys123",
"UseBoolPropertiesWithoutDefaultSql": false,
"UseDatabaseNames": false,
"UseDbContextSplitting": false,
"UseFluentApiOnly": false,
"UseHandleBars": false,
"UseHierarchyId": false,
"UseInflector": true,
"UseLegacyPluralizer": false,
"UseManyToManyEntity": false,
"UseNoConstructor": false,
"UseNoDefaultConstructor": false,
"UseNoNavigations": false,
"UseNoObjectFilter": false,
"UseNodaTime": false,
"UseNullableReferences": false,
"UseSchemaFolders": false,
"UseSpatial": false
}
\ No newline at end of file

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 16
VisualStudioVersion = 16.0.30804.86
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ApiSys", "ApiSys\ApiSys.csproj", "{12A824A5-12D2-4297-A2B7-02B508445F86}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ApiModel", "ApiModel\ApiModel.csproj", "{17EED585-1146-4C91-A5A1-679F491B0463}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ApiCommon", "ApiCommon\ApiCommon.csproj", "{96684B7B-D0AE-4CA2-988F-683FAD03CD8A}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{12A824A5-12D2-4297-A2B7-02B508445F86}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{12A824A5-12D2-4297-A2B7-02B508445F86}.Debug|Any CPU.Build.0 = Debug|Any CPU
{12A824A5-12D2-4297-A2B7-02B508445F86}.Release|Any CPU.ActiveCfg = Release|Any CPU
{12A824A5-12D2-4297-A2B7-02B508445F86}.Release|Any CPU.Build.0 = Release|Any CPU
{17EED585-1146-4C91-A5A1-679F491B0463}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{17EED585-1146-4C91-A5A1-679F491B0463}.Debug|Any CPU.Build.0 = Debug|Any CPU
{17EED585-1146-4C91-A5A1-679F491B0463}.Release|Any CPU.ActiveCfg = Release|Any CPU
{17EED585-1146-4C91-A5A1-679F491B0463}.Release|Any CPU.Build.0 = Release|Any CPU
{96684B7B-D0AE-4CA2-988F-683FAD03CD8A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{96684B7B-D0AE-4CA2-988F-683FAD03CD8A}.Debug|Any CPU.Build.0 = Debug|Any CPU
{96684B7B-D0AE-4CA2-988F-683FAD03CD8A}.Release|Any CPU.ActiveCfg = Release|Any CPU
{96684B7B-D0AE-4CA2-988F-683FAD03CD8A}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {D519DFE9-4A4B-4C3E-8445-3FD1B4716CC9}
VisualSVNWorkingCopyRoot = .
EndGlobalSection
EndGlobal
{
"version": 1,
"isRoot": true,
"tools": {
"dotnet-ef": {
"version": "5.0.2",
"commands": [
"dotnet-ef"
]
}
}
}
\ No newline at end of file
File added
<?xml version="1.0"?>
<doc>
<assembly>
<name>ApiSys</name>
</assembly>
<members>
<member name="M:ApiSys.Common.MyHtmlExten.SearchBtnHtml(Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper,System.String,System.String)">
<summary>
搜索按钮
</summary>
</member>
<member name="M:ApiSys.Common.MyHtmlExten.ResetBtnHtml(Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper,System.String,System.String)">
<summary>
重置按钮
</summary>
</member>
<member name="M:ApiSys.Common.MyHtmlExten.RightToolBarHtml(Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper,System.Object)">
<summary>
表格内按钮组
</summary>]
</member>
<member name="M:ApiSys.Common.MyHtmlExten.TopToolBarHtml(Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper,System.Object)">
<summary>
表格外按钮组
</summary>
</member>
<member name="M:ApiSys.Common.MyHtmlExten.EnabledMarkSelectHtml(Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper,System.String)">
<summary>
状态下拉框
</summary>
</member>
<member name="M:ApiSys.Common.MyHtmlExten.GenderRadioHtml(Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper,System.Int32)">
<summary>
性别单选框
</summary>
</member>
<member name="M:ApiSys.Common.MyHtmlExten.EnabledLockHtml(Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper,System.Int32)">
<summary>
状态单选框
</summary>
</member>
<member name="M:ApiSys.Common.MyHtmlExten.ReturnMarkRadioHtml(Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper,System.Int32)">
<summary>
反量单选框
</summary>
</member>
<member name="M:ApiSys.Controllers.LoginController.GetAppKey(System.String)">
<summary>
生成APPKEY
</summary>
<returns></returns>
</member>
<member name="M:ApiSys.Controllers.LoginController.GetSecretKey(System.String)">
<summary>
生成SecretKey
</summary>
<param name="userName"></param>
<returns></returns>
</member>
<member name="M:ApiSys.Controllers.OrganizeController.GetOrganizeChildren(System.Collections.Generic.List{ApiSys.Models.TreeSelect},System.Collections.Generic.List{ApiModel.Entity.SysOrg},ApiSys.Models.TreeSelect,System.String)">
<summary>
递归遍历treeSelectList
</summary>
</member>
<member name="T:ApiSys.Models.PositionEnum">
<summary>
显示位置枚举
</summary>
</member>
<member name="F:ApiSys.Models.PositionEnum.FormInside">
<summary>
表内
</summary>
</member>
<member name="F:ApiSys.Models.PositionEnum.FormRightTop">
<summary>
表外
</summary>
</member>
<member name="M:Mx.Web.Areas.Permissions.Controllers.ModuleController.GetModuleListByModuleId(System.Collections.Generic.List{ApiSys.Models.ModuleTree},System.Collections.Generic.IEnumerable{ApiModel.Entity.SysModule},ApiSys.Models.ModuleTree,System.String)">
<summary>
根据一级菜单加载子菜单列表
</summary>
<param name="treeList"></param>
<param name="allMenus"></param>
<param name="tree"></param>
<param name="moduleId"></param>
</member>
<member name="M:Mx.Web.Areas.Permissions.Controllers.ModuleController.GetModuleButtonList(System.String)">
<summary>
获取所有菜单列表及可用按钮权限列表
</summary>
<param name="roleId">角色ID</param>
<returns></returns>
</member>
<member name="M:Mx.Web.Areas.Permissions.Controllers.ModuleController.GetModuleChildren(System.Collections.Generic.List{ApiSys.Models.TreeSelect},System.Collections.Generic.List{ApiModel.Entity.SysModule},ApiSys.Models.TreeSelect,System.String)">
<summary>
递归遍历treeSelectList
</summary>
</member>
</members>
</doc>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace ApiSys.Common
{
public interface IVerCodePolicy
{
void ClearCode(string key);
bool IsGenCode(string key, out byte[] buffer);
void InsertCode(string key, byte[] buffer,string verCode);
string GetVerCode(string key);
}
public class VerCodePolicy : IVerCodePolicy
{
public VerCodePolicy()
{
c_policy = new CancellationTokenSource();
task_policy = Task.Run(() =>
{
while (!c_policy.IsCancellationRequested)
{
lock (lockObj)
{
foreach (var item in dict_cache.ToList())
{
var vle_info = item.Value;
if (vle_info.LastDate.Subtract(DateTime.Now).TotalMinutes > 5)
{
dict_cache.Remove(item.Key);
}
else
{
continue;
}
}
}
if (resetEvent.WaitOne(600 * 1000))
{
break;
}
}
});
}
private AutoResetEvent resetEvent = new AutoResetEvent(false);
private Task task_policy;
private Dictionary<string, string> dic_black = new Dictionary<string, string>();
private object lockObj = new object();
private CancellationTokenSource c_policy;
private Dictionary<string, VerInfo> dict_cache = new Dictionary<string, VerInfo>();
public void InsertCode(string key, byte[] buffer,string verCode)
{
if (!dict_cache.ContainsKey(key))
{
dict_cache.Add(key, new VerInfo { Buffer = buffer, LastDate = DateTime.Now,VerCode= verCode });
}
else
{
dict_cache[key].VerCode = verCode;
dict_cache[key].LastDate = DateTime.Now;
dict_cache[key].Buffer = buffer;
}
}
public string GetVerCode(string key)
{
if (!dict_cache.ContainsKey(key))
{
return string.Empty;
}
else
{
return dict_cache[key].VerCode;
}
}
public bool IsGenCode(string key, out byte[] buffer)
{
lock (lockObj)
{
if (dict_cache.ContainsKey(key))
{
var last_date = dict_cache[key].LastDate;
if (DateTime.Now.Subtract(last_date).TotalSeconds > 1.5)
{
buffer = default;
return true;
}
else
{
buffer = dict_cache[key].Buffer;
return false;
}
}
else
{
buffer = default;
return true;
}
}
}
public void ClearCode(string key)
{
if (dict_cache.ContainsKey(key))
{
dict_cache[key].Buffer = new byte[] { };
dict_cache[key].LastDate = DateTime.Now.Date;
dict_cache.Remove(key);
}
}
}
public class VerInfo
{
public string VerCode { get; set; }
public DateTime LastDate { get; set; }
public byte[] Buffer { get; set; }
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace ApiSys.Common
{
public class MainInfo: WebInfo
{
public string UserName { get; set; }
public string HeadIco { get; set; }
public string Account { get; set; }
public string UserId { get; set; }
}
}
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace ApiSys.Common
{
public static class MyExtensions
{
public static string GetSession(this ISession session, string key)
{
bool flag = session.TryGetValue(key, out byte[] res);
if (flag) { return Encoding.UTF8.GetString(res); }
else
{
return string.Empty;
}
}
}
}
using ApiModel.Entity;
using Microsoft.AspNetCore.Html;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ApiSys.Common
{
public static class MyHtmlExten
{
/// <summary>
/// 搜索按钮
/// </summary>
public static HtmlString SearchBtnHtml(this IHtmlHelper helper, string title = "搜索", string _class = "")
{
return new HtmlString(string.Format(@"<button class='layui-btn {1}' lay-submit='' lay-filter='search'>
<i class='layui-icon'>&#xe615;</i>{0}
</button>", title, _class));
}
/// <summary>
/// 重置按钮
/// </summary>
public static HtmlString ResetBtnHtml(this IHtmlHelper helper, string title = "重置", string _class = "layui-btn-primary")
{
return new HtmlString(string.Format(@"<button type='reset' id='reset' class='layui-btn {1}'>{0}</button>", title, _class));
}
/// <summary>
/// 表格内按钮组
/// </summary>]
public static HtmlString RightToolBarHtml(this IHtmlHelper helper, dynamic _list = null)
{
StringBuilder sb = new StringBuilder();
var list = _list as List<SysButton>;
if (list != null && list.Count > 0)
{
foreach (var item in list)
{
sb.AppendLine(string.Format(@"<a class='layui-btn layui-btn-xs {0}' href='javascript:;' lay-event='{1}' id='{1}'><i class='ok-icon'>{3}</i>{2}</a>", item.ClassName, item.Code, item.Name, item.Icon));
}
}
return new HtmlString(sb.ToString());
}
/// <summary>
/// 表格外按钮组
/// </summary>
public static HtmlString TopToolBarHtml(this IHtmlHelper helper, dynamic _list = null)
{
StringBuilder sb = new StringBuilder();
var list = _list as List<SysButton>;
if (list != null && list.Count > 0)
{
foreach (var item in list)
{
sb.AppendLine(string.Format(@"<button class='layui-btn layui-btn-sm {0}' lay-event='{1}' id='{1}'><i class='ok-icon'>{3}</i>{2}</button>", item.ClassName, item.Code, item.Name, item.Icon));
}
}
return new HtmlString(sb.ToString());
}
/// <summary>
/// 状态下拉框
/// </summary>
public static HtmlString EnabledMarkSelectHtml(this IHtmlHelper helper, string defaultTxt = "")
{
return new HtmlString(string.Format(@"<div class='layui-input-inline'>
<select name='EnabledMark'>
<option value=''>{0}</option>
<option value='0'>启用</option >
<option value='1'>禁用</option >
</select>
</div>", defaultTxt));
}
/// <summary>
/// 性别单选框
/// </summary>
public static HtmlString GenderRadioHtml(this IHtmlHelper helper, int defaultVal = 1)
{
var male = defaultVal == 1 ? "checked" : "";
var female = defaultVal == 0 ? "checked" : "";
return new HtmlString(string.Format(@"<div class='layui-form-item' pane>
<label class='layui-form-label'>性别</label>
<div class='layui-input-block'>
<input type='radio' name='Sex' value='1' title='男' {0}>
<input type='radio' name='Sex' value='0' title='女' {1}>
</div>
</div>", male, female));
}
/// <summary>
/// 状态单选框
/// </summary>
public static HtmlString EnabledLockHtml(this IHtmlHelper helper, int defaultVal = 0)
{
var enabled = defaultVal == 0 ? "checked" : "";
var disabled = defaultVal == 1 ? "checked" : "";
return new HtmlString(string.Format(@"<div class='layui-form-item' pane>
<label class='layui-form-label'>状态</label>
<div class='layui-input-block'>
<input type='radio' name='IsLock' value='0' title='开启' {0}>
<input type='radio' name='IsLock' value='1' title='禁用' {1}>
</div>
</div>", enabled, disabled));
}
/// <summary>
/// 反量单选框
/// </summary>
public static HtmlString ReturnMarkRadioHtml(this IHtmlHelper helper, int defaultVal = 0)
{
var enabled = defaultVal == 0 ? "checked" : "";
var disabled = defaultVal == 1 ? "checked" : "";
return new HtmlString(string.Format(@"<div class='layui-form-item' pane>
<label class='layui-form-label'>是否反量</label>
<div class='layui-input-block'>
<input type='radio' name='IsRet' value='0' title='开启' {0}>
<input type='radio' name='IsRet' value='1' title='禁用' {1}>
</div>
</div>", enabled, disabled));
}
}
}
using ApiModel.Entity;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;
namespace ApiSys.Common
{
public class SysMoudleExten:SysModule
{
[NotMapped]
public bool IsChecked { get; set; }
[NotMapped]
public string ModuleButtonHtml { get; set; }
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace ApiSys.Common
{
public class UserCookie
{
public string UserName { get; set; }
public string UserId { get; set; }
public string HeadIcon { get; set; }
public string Account { get; set; }
public string RoleId { get; set; }
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace ApiSys.Common
{
public class WebInfo
{
/// <summary>
/// 网站标题
/// </summary>
public string SiteTitle { get; set; }
/// <summary>
/// 联系邮箱
/// </summary>
public string Email { get; set; }
/// <summary>
/// 版权信息
/// </summary>
public string CopyRight { get; set; }
/// <summary>
/// 上传文件大小
/// </summary>
public long UploadSize { get; set; }
/// <summary>
/// 重置默认密码
/// </summary>
public string InitUserPwd { get; set; }
/// <summary>
/// 注册用户默认角色
/// </summary>
public string RegRole { get; set; }
/// <summary>
/// 审核通过默认角色
/// </summary>
public string PassRole { get; set; }
/// <summary>
/// 超级管理员角色
/// </summary>
public string AdminRole { get; set; }
/// <summary>
/// 注册用户默认部门
/// </summary>
public string RegDepart { get; set; }
/// <summary>
/// 超级管理员ID
/// </summary>
public string AdminId { get; set; }
}
}
using ApiCommon;
using ApiModel.Basic;
using ApiModel.Entity;
using ApiSys.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Text.RegularExpressions;
namespace ApiSys.Controllers
{
public class ApiSrcController : BaseController
{
protected UnitOfWork ofWork;
public ApiSrcController(UnitOfWork unitOfWork) : base(unitOfWork)
{
this.ofWork = unitOfWork;
}
public SelectList AppList { get { return new SelectList(ofWork.SysAppsRepository.GetList(t => t.UserId == Operator.UserId).ToList(), "AppType", "Name"); } }
public IActionResult MySrc()
{
ViewBag.AppList = AppList;
return View();
}
[HttpGet]
public JsonResult List(ApiSrc model, PageInfo pageInfo)
{
Expression<Func<ApiSrc, bool>> expression = t => t.Id != "";
if (!string.IsNullOrEmpty(model.Name))
{
expression = MyLambda.And(expression, t => t.Name.Contains(model.Name));
}
if (!string.IsNullOrEmpty(model.Url))
{
expression = MyLambda.And(expression, t => t.Url.Contains(model.Url));
}
var result = ofWork.ApiSrcRepository.GetPage(expression, pageInfo.page, pageInfo.limit, "-CreateTime");
var list = result?.data.Select(s => new
{
CreateTime = (s.CreateTime == null ? default(DateTime) : s.CreateTime.Value).ToString("yyyy-MM-dd HH:mm"),
s.Name,
s.Id,
s.Type,
s.DemoText,
s.Url
}).ToList();
return Json(Pager.Paging(list, result.total));
}
[HttpGet]
public JsonResult MyList(SysApp model, PageInfo pageInfo)
{
Expression<Func<VAppApi, bool>> expression = t => t.UserId == Operator.UserId;
if (!string.IsNullOrEmpty(model.AppType))
{
expression = MyLambda.And(expression, t => t.AppType == model.AppType);
}
if (!string.IsNullOrEmpty(model.Name))
{
expression = MyLambda.And(expression, t => t.Name.Contains(model.Name));
}
var result = ofWork.VAppApiRepository.GetPage(expression, pageInfo.page, pageInfo.limit);
return Json(Pager.Paging(result));
}
public IActionResult Add()
{
return View();
}
[HttpPost]
public IActionResult Add(ApiSrc model)
{
model.Id = Guid.NewGuid().ToString();
model.CreateTime = DateTime.Now;
var result = ofWork.ApiSrcRepository.Insert(model) ? SuccessTip("添加成功") : ErrorTip("添加失败");
return Json(result);
}
public IActionResult Edit(string id)
{
var model = ofWork.ApiSrcRepository.Get(id);
return View(model);
}
[HttpPost]
public IActionResult Edit(ApiSrc model)
{
var result = ofWork.ApiSrcRepository.Update(model) ? SuccessTip("修改成功") : ErrorTip("修改失败");
return Json(result);
}
[HttpGet]
public JsonResult Delete(string id)
{
ofWork.SysAppApiRepository.Delete(t => t.ApiId == id, false);
ofWork.SysAppTypeApiRepository.Delete(t => t.ApiId == id, false);
var result = ofWork.ApiSrcRepository.Delete(t => t.Id == id, true) ? SuccessTip("删除成功") : ErrorTip("删除失败");
return Json(result);
}
[HttpPost]
public JsonResult ImportApiJson()
{
var json = Request.Form.Files.FirstOrDefault();
if (json == null)
{
return Json(ErrorTip("上传失败"));
}
else
{
var ext = Path.GetExtension(json.FileName).ToLower();
if (ext != ".json")
{
return Json(ErrorTip("上传失败,不正确的文件类型"));
}
else
{
using (MemoryStream ms = new MemoryStream())
{
//拷贝文件到内存流
json.CopyTo(ms);
var res = GetSwaggerJson(Encoding.UTF8.GetString(ms.ToArray()));
if (res == null)
{
return Json(ErrorTip("上传失败,文件解析失败"));
}
else
{
List<DocIns> tmpList = new List<DocIns>();
res.ForEach(s =>
{
tmpList.Add(new DocIns
{
ApiName = s.name.Replace(" ", "").Replace("\n", ""),
ApiType = s.type.ToUpper(),
ApiUrl = s.url,
DemoText = s.demo.Replace("\r", "").Replace("\n", "").Replace(" ", "")
});
});
var all = ofWork.ApiSrcRepository.GetList().ToList();
tmpList.ForEach(s =>
{
var tmp = all.FirstOrDefault(t => t.Url == s.ApiUrl);
if (tmp != null)
{
Expression<Func<ApiSrc, object>>[] updatedProperties = { p => p.Type, p => p.Name };
tmp.Type = s.ApiType;
tmp.Name = s.ApiName;
ofWork.ApiSrcRepository.Update(tmp, updatedProperties, false);
}
else
{
ofWork.ApiSrcRepository.Insert(new ApiSrc
{
Id = Guid.NewGuid().ToString(),
CreateTime = DateTime.Now,
DemoText = s.DemoText,
Name = s.ApiName,
Url = s.ApiUrl,
Isdel = false,
Type = s.ApiType
}, false);
}
});
return Json(ofWork.ApiSrcRepository.SaveChanges() > 0 ? SuccessTip("导入成功") : ErrorTip("导入失败,未能正确保存数据"));
}
}
}
}
}
[HttpGet]
public JsonResult BatchDel(string ids)
{
try
{
if (string.IsNullOrEmpty(ids))
{
return Json(ErrorTip("未选中要删除的数据"));
}
else
{
var tmpList = new List<string>(ids.Split(','));
ofWork.SysAppApiRepository.Delete(t => tmpList.Contains(t.ApiId), false);
ofWork.SysAppTypeApiRepository.Delete(t => tmpList.Contains(t.ApiId), false);
var res = ofWork.ApiSrcRepository.Delete(t => tmpList.Contains(t.Id), true);
var result = res ? SuccessTip("批量删除成功") : ErrorTip("批量删除失败");
return Json(result);
}
}
catch
{
return Json(ErrorTip("批量删除失败"));
}
}
private List<SwgJson> GetSwaggerJson(string json)
{
List<SwgJson> tmpList = new List<SwgJson>();
JObject obj = JObject.Parse(json);
if (obj["paths"].HasValues)
{
var apis = (JObject)obj["paths"];
foreach (var item in apis)
{
if (item.Value["post"]?.HasValues ?? false)
{
var name = item.Value["post"]["summary"]?.ToString() ?? "";
var demo = item.Value["post"]["description"]?.ToString() ?? "";
tmpList.Add(new SwgJson()
{
url = item.Key,
name = name,
demo = demo,
type = "POST"
});
}
else if (item.Value["get"].HasValues)
{
var name = item.Value["get"]["summary"]?.ToString() ?? "";
var demo = item.Value["get"]["description"]?.ToString() ?? "";
tmpList.Add(new SwgJson()
{
url = item.Key,
name = name,
demo = demo,
type = "GET"
});
}
else { }
}
}
return tmpList;
}
}
}
\ No newline at end of file
using ApiCommon;
using ApiModel.Basic;
using ApiModel.Entity;
using ApiSys.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Security.Cryptography;
using System.Text;
namespace ApiSys.Controllers
{
public class AppsController : BaseController
{
protected UnitOfWork ofWork;
public SelectList AppTypeList
{
get
{
return new SelectList(ofWork.SysAppsTypeRepository.GetList(x => string.IsNullOrEmpty(x.LimitUserId) || x.LimitUserId == Operator.UserId).ToList()
, "Id", "Name");
}
}
public AppsController(UnitOfWork unitOfWork) : base(unitOfWork)
{
this.ofWork = unitOfWork;
}
[HttpGet]
public JsonResult List(SysApp model, PageInfo pageInfo)
{
Expression<Func<SysApp, bool>> expression = t => t.Id != "";
if (Operator.RoleId != "9F070D5A-6278-444F-ADF5-B961DDDA8A9F")
{
expression = MyLambda.And(expression, t => t.UserId == Operator.UserId);
}
if (!string.IsNullOrEmpty(model.Name))
{
expression = MyLambda.And(expression, t => t.Name.Contains(model.Name));
}
var result = ofWork.SysAppsRepository.GetPage(expression, pageInfo.page, pageInfo.limit, "SortCode", false, new string[] { "AppTypeNavigation", "User" });
var list = result?.data.Select(s => new
{
s.Appkey,
UserName = s.User.Name,
s.SecretKey,
CreateTime = (s.CreateTime == null ? default(DateTime) : s.CreateTime.Value).ToString("yyyy-MM-dd HH:mm"),
s.Name,
s.Id,
s.AppType,
AppTypeName = s.AppTypeNavigation?.Name,
s.SortCode
}).ToList();
return Json(Pager.Paging(list, result.total));
}
public IActionResult Add()
{
ViewBag.AppTypeList = AppTypeList;
return View();
}
[HttpPost]
public IActionResult Add(SysApp model)
{
if (ofWork.SysAppsRepository.Any(t => t.UserId == Operator.UserId && t.AppType == model.AppType))
{
return Json(ErrorTip("同一类型的应用只能创建一个!"));
}
else
{
string now_date = DateTime.Now.ToString("yyyyMMddHHmmssfff") + "junmp_api_sys";
model.Id = Guid.NewGuid().ToString();
model.UserId = Operator.UserId;
model.Appkey = GetAppKey(now_date);
model.SecretKey = GetSecretKey(now_date);
model.CreateTime = DateTime.Now;
var result = ofWork.SysAppsRepository.Insert(model) ? SuccessTip("添加成功") : ErrorTip("添加失败");
return Json(result);
}
}
public IActionResult Edit(string id)
{
ViewBag.AppTypeList = AppTypeList;
var model = ofWork.SysAppsRepository.Get(id);
return View(model);
}
[HttpPost]
public IActionResult Edit(SysApp model)
{
if (ofWork.SysAppsRepository.Any(t => t.UserId == Operator.UserId && t.Id != model.Id && t.AppType == model.AppType))
{
return Json(ErrorTip("同一类型的应用只能创建一个!"));
}
else
{
Expression<Func<SysApp, object>>[] updatedProperties = { p => p.AppType, p => p.Name, p => p.SortCode, p => p.Description };
var result = ofWork.SysAppsRepository.Update(model, updatedProperties) ? SuccessTip("修改成功") : ErrorTip("修改失败");
return Json(result);
}
}
[HttpGet]
public JsonResult Delete(string id)
{
var result = ofWork.SysAppsRepository.Delete(t => t.Id == id) ? SuccessTip("删除成功") : ErrorTip("删除失败");
return Json(result);
}
/// <summary>
/// 生成APPKEY
/// </summary>
/// <returns></returns>
private string GetAppKey(string userName)
{
var _text = userName + DateTime.Now.ToString("yyyyMMddHHmmssfff") + "junmp.com.cn";
byte[] _input = Encoding.UTF8.GetBytes(_text);
using (MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider())
{
byte[] _output = md5.ComputeHash(_input);
var sing = @Convert.ToBase64String(_output);
return sing;
}
}
/// <summary>
/// 生成SecretKey
/// </summary>
/// <param name="userName"></param>
/// <returns></returns>
private string GetSecretKey(string userName)
{
var _text = userName + DateTime.Now.ToString("yyyyMMddHHmmssfff") + "junmp.com.cn";
byte[] _input = Encoding.UTF8.GetBytes(_text);
using (MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider())
{
StringBuilder sb = new StringBuilder();
byte[] _output = md5.ComputeHash(_input);
for (int i = 0; i < _output.Length; i++)
{
sb.Append(_output[i].ToString("x2"));
}
return sb.ToString();
}
}
public IActionResult SetSrc(string appId, string typeId)
{
ViewBag.AppId = appId;
ViewBag.TypeId = typeId;
return View();
}
[HttpPost]
public IActionResult SetSrc(List<SysAppApi> list, string appid)
{
//先删除全部权限
ofWork.SysAppApiRepository.Delete(t => t.AppId == appid, false);
list.ForEach(s =>
{
s.Id = Guid.NewGuid().ToString();
s.AppId = appid;
});
var result = ofWork.SysAppApiRepository.Insert(list, true) ? SuccessTip("保存成功") : ErrorTip("保存失败");
return Json(result);
}
public JsonResult GetAppApis(string appId, string typeId)
{
var type_ids = ofWork.SysAppTypeApiRepository.GetList(t => t.TypeId == typeId).Select(s => s.ApiId).ToList();
var selected = ofWork.SysAppApiRepository.GetList(t => t.AppId == appId).ToList().Select(s => s.ApiId).ToList();
var all = ofWork.ApiSrcRepository.GetList(t => !type_ids.Contains(t.Id)).ToList().Select(x => new
{
Id = x.Id,
Url = x.Url,
Name = x.Name,
SortCode = x.SortCode,
CreateTime = x.CreateTime.Value.ToString("yyyy-MM-dd HH:mm"),
IsChecked = selected.Any(t => t.Contains(x.Id))
});
var result = new { code = 0, count = all.Count(), data = all };
return Json(result);
}
}
}
\ No newline at end of file
using ApiCommon;
using ApiModel.Basic;
using ApiModel.Entity;
using ApiSys.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
namespace ApiSys.Controllers
{
public class AppsTypeController : BaseController
{
protected UnitOfWork ofWork;
public AppsTypeController(UnitOfWork unitOfWork) : base(unitOfWork)
{
this.ofWork = unitOfWork;
}
[HttpGet]
public JsonResult List(SysAppsType model, PageInfo pageInfo)
{
Expression<Func<SysAppsType, bool>> expression = t => t.Id != "";
if (Operator.RoleId != "9F070D5A-6278-444F-ADF5-B961DDDA8A9F")
{
//非管理员
expression = expression.AndAlso(t => string.IsNullOrEmpty(t.LimitUserId) || t.LimitUserId == Operator.UserId);
}
if (!string.IsNullOrEmpty(model.Name))
{
expression = MyLambda.And(expression, t => t.Name.Contains(model.Name));
}
var result = ofWork.SysAppsTypeRepository.GetPage(expression, pageInfo.page, pageInfo.limit, "SortCode");
var list = result?.data.Select(s => new
{
CreateTime = (s.CreateTime == null ? default(DateTime) : s.CreateTime.Value).ToString("yyyy-MM-dd HH:mm"),
s.Name,
s.Id,
s.SortCode
}).ToList();
return Json(Pager.Paging(list, result.total));
}
public IActionResult Add()
{
ViewBag.UserList = new SelectList(ofWork.SysUserRepository.GetList(x => x.IsApprove == "已审核").Select(x => new
{
x.Id,
Name = x.Name + "-" + x.Account
}), "Id", "Name");
return View();
}
[HttpPost]
public IActionResult Add(SysAppsType model)
{
model.Id = Guid.NewGuid().ToString();
model.CreateTime = DateTime.Now;
var result = ofWork.SysAppsTypeRepository.Insert(model) ? SuccessTip("添加成功") : ErrorTip("添加失败");
return Json(result);
}
public IActionResult Edit(string id)
{
var model = ofWork.SysAppsTypeRepository.Get(id);
ViewBag.UserList = new SelectList(ofWork.SysUserRepository.GetList(x => x.IsApprove == "已审核").Select(x => new
{
x.Id,
Name = x.Name + "-" + x.Account
}), "Id", "Name");
return View(model);
}
[HttpPost]
public IActionResult Edit(SysAppsType model)
{
var result = ofWork.SysAppsTypeRepository.Update(model) ? SuccessTip("修改成功") : ErrorTip("修改失败");
return Json(result);
}
[HttpGet]
public JsonResult Delete(string id)
{
var result = ofWork.SysAppsTypeRepository.Delete(t => t.Id == id) ? SuccessTip("删除成功") : ErrorTip("删除失败");
return Json(result);
}
public IActionResult SetSrc(string id)
{
ViewBag.AppTypeId = id;
return View();
}
[HttpPost]
public IActionResult SetSrc(List<SysApptypeApi> list, string typeId)
{
//先删除全部权限
ofWork.SysAppTypeApiRepository.Delete(t => t.TypeId == typeId, false);
list.ForEach(s =>
{
s.Id = Guid.NewGuid().ToString();
s.TypeId = typeId;
});
var result = ofWork.SysAppTypeApiRepository.Insert(list, true) ? SuccessTip("保存成功") : ErrorTip("保存失败");
return Json(result);
}
public JsonResult GetAppTypeApis(string typeId)
{
var selected = ofWork.SysAppTypeApiRepository.GetList(t => t.TypeId == typeId).ToList().Select(s => s.ApiId).ToList();
var all = ofWork.ApiSrcRepository.GetList().ToList().Select(x => new
{
Id = x.Id,
Url = x.Url,
Name = x.Name,
SortCode = x.SortCode,
CreateTime = x.CreateTime.Value.ToString("yyyy-MM-dd HH:mm"),
IsChecked = selected.Contains(x.Id)
});
var result = new { code = 0, count = all.Count(), data = all };
return Json(result);
//return Json(new AjaxResult
//{
// data = new
// {
// left = lefts,
// right = rights
// },
// message = "",
// state = ResultType.success.ToString()
//});
}
}
}
\ No newline at end of file
using ApiCommon;
using ApiModel.Basic;
using ApiSys.Common;
using ApiSys.Models;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
namespace ApiSys.Controllers
{
public class AuthController : Controller
{
public UnitOfWork ofWork;
public WebInfo webInfo;
public AuthController(UnitOfWork _unitOfWork, WebInfo _webInfo)
{
this.webInfo = _webInfo;
this.ofWork = _unitOfWork;
}
[HttpPost]
public JsonResult JpVerification([FromBody] AuthModel model)
{
if (string.IsNullOrEmpty(model.appKey))
{
return Json(JsonManager.CustMsg($"AppKey无效", ResultType.invalid_par));
}
else
{
string[] includes = new string[] { "User", "User.SysUserApiOrgs" };
var appInfo = ofWork.SysAppsRepository.Get(t => t.Appkey == @model.appKey, includes);
if (appInfo != null)
{
//内部应用,直接通过
if (!string.IsNullOrEmpty(appInfo.User.RoleId) && appInfo.User.RoleId.ToLower() == webInfo.AdminRole.ToLower())
{
return Json(JsonManager.CustMsg($"认证成功", ResultType.success));
}
else if (!appInfo.User.SysUserApiOrgs.Any(t => t.OrgId == model.orgId))
{
return Json(JsonManager.CustMsg($"组织机构未授权", ResultType.org_unauthorized));
}
else if (!ofWork.VAppApiRepository.Any(t => t.SecretKey == appInfo.SecretKey && t.Url == model.apiName))
{
return Json(JsonManager.CustMsg($"接口未授权", ResultType.api_unauthorized));
}
else
{
return Json(JsonManager.CustMsg($"认证成功", ResultType.success));
}
}
else
{
return Json(JsonManager.CustMsg($"AppKey未注册", ResultType.unregistered));
}
}
}
[HttpGet]
public JsonResult GetServerTime()
{
return Json(JsonManager.SuccessMsg($"{DateTime.Now:yyyyy-MM-dd HH:mm}"));
}
[HttpGet]
public JsonResult GetSecretKey(string appKey)
{
var appInfo = ofWork.SysAppsRepository.Get(t => t.Appkey == @appKey);
if (appInfo == null)
{
return Json(JsonManager.CustMsg($"AppKey不存在", ResultType.not_extist));
}
else
{
return Json(JsonManager.CustMsg($"获取成功", ResultType.success, appInfo.SecretKey));
}
}
}
}
using ApiCommon;
using ApiModel.Basic;
using ApiSys.Common;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using ApiSys.Models;
using Microsoft.Extensions.Configuration;
namespace ApiSys.Controllers
{
public class BaseController : Controller
{
protected UnitOfWork ofWork;
protected IConfiguration configuration;
public BaseController(UnitOfWork _ofWork)
{
this.ofWork = _ofWork;
}
public BaseController(UnitOfWork _ofWork, IConfiguration _configuration)
{
this.ofWork = _ofWork;
this.configuration = _configuration;
}
public override JsonResult Json(object data)
{
return base.Json(data, new JsonSerializerSettings()
{
DateFormatString = "yyyy-MM-dd HH:mm",
ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
ContractResolver = new DefaultContractResolver(),
StringEscapeHandling = StringEscapeHandling.EscapeNonAscii
});
}
// GET: Base
public virtual IActionResult Index(string id)
{
ViewData["JYZBApi"] = configuration?["JYZBApi"];
var _menuId = id == null ? Guid.Empty.ToString() : id;
var _roleId = Operator.RoleId;
if (!_roleId.IsEmpty())
{
ViewData["RightButtonList"] = ofWork.SysRoleAuthRepository.GetList(t => t.ModuleId == _menuId
&& t.RoleId == _roleId
&& t.Button.Location == (int)PositionEnum.FormInside)
.Select(s => s.Button).OrderBy(t => t.SortCode).ToList();
ViewData["TopButtonList"] = ofWork.SysRoleAuthRepository.GetList(t => t.ModuleId == _menuId
&& t.RoleId == _roleId
&& t.Button.Location == (int)PositionEnum.FormRightTop)
.Select(s => s.Button).OrderBy(t => t.SortCode).ToList();
}
return View();
}
// GET: CheckSession
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
base.OnActionExecuting(filterContext);
//这里判断出没有登录然后进行跳转
if (!filterContext.HttpContext.User.Claims.Any(t => t.Type == "roleId"))
{
Response.Redirect("/Login/Index");
}
}
protected UserCookie Operator
{
get
{
UserCookie user = new UserCookie();
foreach (var item in HttpContext.User.Claims)
{
if (item.Type == "userName")
{
user.UserName = item.Value;
}
if (item.Type == "userId")
{
user.UserId = item.Value;
}
if (item.Type == "userAccount")
{
user.Account = item.Value;
}
if (item.Type == "roleId")
{
user.RoleId = item.Value;
}
if (item.Type == "headIcon")
{
user.HeadIcon = item.Value;
}
}
return user;
}
}
public AjaxResult SuccessTip(string msg = "操作成功")
{
return JsonManager.SuccessMsg(msg);
}
public AjaxResult ErrorTip(string msg = "操作失败")
{
return JsonManager.ErrorMsg(msg);
}
}
}
using ApiCommon;
using ApiModel.Basic;
using ApiModel.Entity;
using ApiSys.Models;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
namespace ApiSys.Controllers
{
public class ButtonController : BaseController
{
public ButtonController(UnitOfWork unitOfWork) : base(unitOfWork)
{
this.ofWork = unitOfWork;
}
[HttpGet]
public JsonResult List(SysButton model, PageInfo pageInfo)
{
Expression<Func<SysButton, bool>> expression = t => t.Id != Guid.Empty.ToString();
if (!string.IsNullOrEmpty(model.Name))
{
expression = MyLambda.And(expression, t => t.Name.Contains(model.Name));
}
var result = ofWork.SysButtonRepository.GetPage(expression, pageInfo.page, pageInfo.limit, "SortCode");
var list = result?.data.Select(s => new
{
ClassName = s.ClassName,
CreateTime = (s.CreateTime == null ? default(DateTime) : s.CreateTime.Value).ToString("yyyy-MM-dd HH:mm"),
Code = s.Code,
Name = s.Name,
Icon = s.Icon,
Id = s.Id,
Location = s.Location,
SortCode = s.SortCode
}).ToList();
return Json(Pager.Paging(list, result.total));
}
public ActionResult Add()
{
return View();
}
[HttpPost]
public ActionResult Add(SysButton model)
{
model.Id = Guid.NewGuid().ToString();
model.CreateTime = DateTime.Now;
var result = ofWork.SysButtonRepository.Insert(model) ? SuccessTip("添加成功") : ErrorTip("添加失败");
return Json(result);
}
public ActionResult Edit(string id)
{
var model = ofWork.SysButtonRepository.Get(id);
return View(model);
}
[HttpPost]
public ActionResult Edit(SysButton model)
{
var result = ofWork.SysButtonRepository.Update(model) ? SuccessTip("修改成功") : ErrorTip("修改失败");
return Json(result);
}
[HttpGet]
public JsonResult Delete(string id)
{
var result = ofWork.SysButtonRepository.Delete(t => t.Id == id) ? SuccessTip("删除成功") : ErrorTip("删除失败");
return Json(result);
}
}
}
using ApiCommon;
using ApiModel.Basic;
using ApiModel.Entity;
using ApiSys.Models;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
namespace ApiSys.Controllers
{
public class CommonController : Controller
{
public CommonController()
{
}
public IActionResult Icon()
{
return View();
}
}
}
using ApiCommon;
using ApiModel.Basic;
using ApiModel.Entity;
using ApiSys.Common;
using ApiSys.Models;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Security.Claims;
using System.Threading.Tasks;
namespace ApiSys.Controllers
{
public class HomeController : BaseController
{
protected UnitOfWork ofWork;
protected WebInfo webInfo;
public HomeController(UnitOfWork unitOfWork, WebInfo info) : base(unitOfWork)
{
this.ofWork = unitOfWork;
this.webInfo = info;
}
public override IActionResult Index(string id)
{
ViewBag.Title = webInfo.SiteTitle;
ViewBag.Account = Operator?.Account;
ViewBag.HeadIcon = Operator?.HeadIcon;
ViewBag.CopyRight = webInfo.CopyRight;
ViewBag.Email = webInfo.Email;
ViewBag.SiteTitle = webInfo.SiteTitle;
ViewBag.UserName = Operator?.UserName;
ViewBag.UserId = Operator?.UserId;
return base.View(id);
}
[HttpGet]
public JsonResult LogList(SysLoginlog model, PageInfo pageInfo)
{
Expression<Func<SysLoginlog, bool>> expression = t => t.Id != Guid.Empty.ToString();
if (Operator.RoleId != webInfo.AdminRole)
{
expression = MyLambda.And(expression, t => t.Account == Operator.Account);
}
if (!string.IsNullOrEmpty(model.UserName))
{
expression = MyLambda.And(expression, t => t.UserName.Contains(model.UserName));
}
var result = ofWork.SysLoginlogRepository.GetPage(expression, pageInfo.page, pageInfo.limit, "-CreateTime");
var list = result?.data.Select(s => new
{
CreateTime = (s.CreateTime == null ? default(DateTime) : s.CreateTime.Value).ToString("yyyy-MM-dd HH:mm"),
Id = s.Id,
s.IpAddress,
s.Reason,
s.Status,
s.UserName,
s.Account
}).ToList();
return Json(Pager.Paging(list, result.total));
}
}
}
using ApiCommon;
using ApiModel.Basic;
using ApiModel.Entity;
using ApiSys.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using ApiSys.Extensions;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
namespace ApiSys.Controllers
{
public class MQTTLogController : BaseController
{
protected UnitOfWork ofWork;
protected IConfiguration configuration;
public MQTTLogController(UnitOfWork unitOfWork, IConfiguration configuration) : base(unitOfWork, configuration)
{
this.ofWork = unitOfWork;
this.configuration = configuration;
}
public IActionResult Detail(string id)
{
ViewBag.Id = id;
ViewData["JYZBApi"] = configuration?["JYZBApi"];
return View();
}
}
}
\ No newline at end of file
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ApiCommon;
using ApiModel.Basic;
using ApiModel.Entity;
using ApiSys.Common;
using ApiSys.Controllers;
using ApiSys.Models;
using Microsoft.AspNetCore.Mvc;
namespace Mx.Web.Areas.Permissions.Controllers
{
public class ModuleController : BaseController
{
protected UnitOfWork ofWork;
public ModuleController(UnitOfWork unitOfWork) : base(unitOfWork)
{
this.ofWork = unitOfWork;
}
[HttpGet]
public JsonResult List()
{
var list = ofWork.SysModuleRepository.GetList().ToList().Select(s => new
{
CreateTime = (s.CreateTime == null ? default(DateTime) : s.CreateTime.Value).ToString("yyyy-MM-dd HH:mm"),
FontFamily = s.FontFamily,
Name = s.Name,
Icon = s.Icon,
SortCode = s.SortCode,
Id = s.Id,
IsChecked = false,
ModuleButtonHtml = string.Empty,
ParentId = s.ParentId == Guid.Empty.ToString() ? "0" : s.ParentId,
UrlAddress = s.UrlAddress
}).ToList();
var result = new { code = 0, count = list.Count(), data = list };
return Json(result);
}
[HttpGet]
public JsonResult GetModuleList()
{
var allMenus = ofWork.SysModuleRepository.GetList(t => t.SysRoleAuths.Any(s => s.RoleId == Operator.RoleId)).ToList();
List<ModuleTree> treeList = new List<ModuleTree>();
var rootMenus = allMenus.Where(x => x.ParentId == Guid.Empty.ToString()).OrderBy(x => x.SortCode);
foreach (var item in rootMenus)
{
var _tree = new ModuleTree { id = item.Id, title = item.Name, href = item.UrlAddress, fontFamily = item.FontFamily, icon = item.Icon };
GetModuleListByModuleId(treeList, allMenus, _tree, item.Id);
treeList.Add(_tree);
}
return Json(treeList);
}
[HttpGet]
public JsonResult GetModuleTreeSelect()
{
List<SysModule> moduleList = ofWork.SysModuleRepository.GetList("SortCode").ToList();
var rootModuleList = moduleList.Where(x => x.ParentId == Guid.Empty.ToString()).OrderBy(x => x.SortCode);
List<TreeSelect> treeSelectList = new List<TreeSelect>();
foreach (var item in rootModuleList)
{
TreeSelect tree = new TreeSelect
{
id = item.Id,
name = item.Name,
open = false
};
GetModuleChildren(treeSelectList, moduleList, tree, item.Id);
treeSelectList.Add(tree);
}
return Json(treeSelectList);
}
public ActionResult Add()
{
return View();
}
[HttpPost]
public ActionResult Add(SysModule model)
{
model.Id = Guid.NewGuid().ToString();
model.FontFamily = "ok-icon";
model.CreateTime = DateTime.Now;
var result = ofWork.SysModuleRepository.Insert(model) ? SuccessTip("添加成功") : ErrorTip("添加失败");
return Json(result);
}
public ActionResult Edit(string id)
{
var model = ofWork.SysModuleRepository.Get(id);
return View(model);
}
[HttpPost]
public ActionResult Edit(SysModule module)
{
var result = ofWork.SysModuleRepository.Update(module) ? SuccessTip("修改成功") : ErrorTip("修改失败");
return Json(result);
}
[HttpGet]
public JsonResult Delete(string id)
{
var result = ofWork.SysModuleRepository.Delete(t => t.Id == id) ? SuccessTip("删除成功") : ErrorTip("删除失败");
return Json(result);
}
/// <summary>
/// 根据一级菜单加载子菜单列表
/// </summary>
/// <param name="treeList"></param>
/// <param name="allMenus"></param>
/// <param name="tree"></param>
/// <param name="moduleId"></param>
private void GetModuleListByModuleId(List<ModuleTree> treeList, IEnumerable<SysModule> allMenus, ModuleTree tree, string moduleId)
{
var childMenus = allMenus.Where(x => x.ParentId == moduleId).OrderBy(x => x.SortCode);
if (childMenus != null && childMenus.Count() > 0)
{
List<ModuleTree> _children = new List<ModuleTree>();
foreach (var item in childMenus)
{
var _tree = new ModuleTree { id = item.Id, title = item.Name, href = item.UrlAddress, fontFamily = item.FontFamily, icon = item.Icon };
_children.Add(_tree);
tree.children = _children;
GetModuleListByModuleId(treeList, allMenus, _tree, item.Id);
}
}
}
[HttpGet]
public JsonResult ModuleButtonList(string roleId)
{
var list = GetModuleButtonList(roleId);
var result = new { code = 0, count = list.Count(), data = list };
return Json(result);
}
/// <summary>
/// 获取所有菜单列表及可用按钮权限列表
/// </summary>
/// <param name="roleId">角色ID</param>
/// <returns></returns>
public List<SysMoudleExten> GetModuleButtonList(string roleId)
{
string[] includes = new string[] { "SysRoleAuths" };
List<SysModule> list = ofWork.SysModuleRepository.GetList("-SortCode", includes).ToList();
return list.Select(s => new SysMoudleExten
{
Icon = s.Icon,
SortCode = s.SortCode,
Id = s.Id,
CreateTime = s.CreateTime,
FontFamily = s.FontFamily,
Name = s.Name,
IsChecked = s.SysRoleAuths.Any((t => t.ModuleId == s.Id && t.RoleId == roleId)),
ModuleButtonHtml = GetButtonListHtmlByRoleIdModuleId(roleId, s.Id),
ParentId = s.ParentId == Guid.Empty.ToString() ? "0" : s.ParentId,
UrlAddress = s.UrlAddress
}).ToList();
}
public string GetButtonListHtmlByRoleIdModuleId(string roleId, string moduleId)
{
var selectList = ofWork.SysRoleAuthRepository.GetList(t => t.RoleId == roleId
&& t.ModuleId == moduleId).Where(s => !string.IsNullOrEmpty(s.ButtonId)).Select(s => s.Button).ToList();
var allList = ofWork.SysButtonRepository.GetList("SortCode").ToList();
StringBuilder sb = new StringBuilder();
if (allList != null && allList.Count() > 0)
{
foreach (var item in allList)
{
var checkedStr = selectList.FirstOrDefault(x => x.Id == item.Id) == null ? "" : "checked";
sb.AppendFormat("<input name='cbx_{0}' class='layui-btn layui-btn-sm' lay-skin='primary' value='{1}' title='{2}' type='checkbox' {3}>", moduleId, item.Id, item.Name, checkedStr);
}
}
return sb.ToString();
}
/// <summary>
/// 递归遍历treeSelectList
/// </summary>
private void GetModuleChildren(List<TreeSelect> treeSelectList, List<SysModule> moduleList, TreeSelect tree, string id)
{
var childModuleList = moduleList.Where(x => x.ParentId == id).OrderBy(x => x.SortCode);
if (childModuleList != null && childModuleList.Count() > 0)
{
List<TreeSelect> _children = new List<TreeSelect>();
foreach (var item in childModuleList)
{
TreeSelect _tree = new TreeSelect
{
id = item.Id,
name = item.Name,
open = false
};
_children.Add(_tree);
tree.children = _children;
GetModuleChildren(treeSelectList, moduleList, _tree, item.Id);
}
}
}
}
}
\ No newline at end of file
using System;
using System.Collections.Generic;
using System.Linq;
using ApiModel.Basic;
using ApiModel.Entity;
using ApiSys.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
namespace ApiSys.Controllers
{
public class OrganizeController : BaseController
{
protected UnitOfWork ofWork;
public OrganizeController(UnitOfWork unitOfWork) : base(unitOfWork)
{
this.ofWork = unitOfWork;
}
[HttpGet]
public JsonResult List()
{
var list = ofWork.SysOrgRepository.GetList().Select(s => new
{
s.Id,
ParentId = string.IsNullOrEmpty(s.ParentId) ? "00000000-0000-0000-0000-000000000000" : s.ParentId,
s.Code,
s.Name,
s.SortCode,
CreateTime = (s.CreateTime == null ? default(DateTime) : s.CreateTime.Value).ToString("yyyy-MM-dd HH:mm"),
});
var result = new { code = 0, count = list.Count(), data = list.ToList() };
return Json(result);
}
[HttpGet]
public JsonResult GetOrganizeTreeSelect(string id)
{
var orgList = ofWork.SysOrgRepository.GetList(t => string.IsNullOrEmpty(id) || !t.Id.Contains(id), "SortCode").ToList();
var rootInfo = orgList.FirstOrDefault(t => t.ParentId == null || t.ParentId == "00000000-0000-0000-0000-000000000000");
List<TreeSelect> treeSelectList = new List<TreeSelect>();
TreeSelect tree = new TreeSelect
{
id = rootInfo.Id,
name = rootInfo.Name,
open = true
};
foreach (var item in orgList)
{
GetOrganizeChildren(orgList, tree, item.Id);
}
treeSelectList.Add(tree);
return Json(treeSelectList);
}
public ActionResult Add()
{
return View();
}
[HttpPost]
public ActionResult Add(SysOrg model)
{
model.Id = Guid.NewGuid().ToString();
model.CreateTime = DateTime.Now;
var result = ofWork.SysOrgRepository.Insert(model) ? SuccessTip("添加成功") : ErrorTip("添加失败");
return Json(result);
}
public ActionResult Edit(string id)
{
var model = ofWork.SysOrgRepository.Get(id);
return View(model);
}
[HttpPost]
public ActionResult Edit(SysOrg model)
{
var result = ofWork.SysOrgRepository.Update(model) ? SuccessTip("修改成功") : ErrorTip("修改失败");
return Json(result);
}
[HttpGet]
public JsonResult Delete(string id)
{
var result = ofWork.SysOrgRepository.Delete(t => t.Id == id) ? SuccessTip("删除成功") : ErrorTip("删除失败");
return Json(result);
}
/// <summary>
/// 递归遍历treeSelectList
/// </summary>
private void GetOrganizeChildren(List<SysOrg> organizeList, TreeSelect tree, string id)
{
var childOrganizeList = organizeList.Where(x => x.ParentId == id).OrderBy(x => x.SortCode);
if (childOrganizeList != null && childOrganizeList.Count() > 0)
{
List<TreeSelect> _children = new List<TreeSelect>();
foreach (var item in childOrganizeList)
{
TreeSelect _tree = new TreeSelect
{
id = item.Id,
name = item.Name,
open = false
};
_children.Add(_tree);
tree.children = _children;
GetOrganizeChildren(organizeList, _tree, item.Id);
}
}
}
}
}
\ No newline at end of file
using ApiCommon;
using ApiModel.Basic;
using ApiModel.Entity;
using ApiSys.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
namespace ApiSys.Controllers
{
public class RoleController : BaseController
{
protected UnitOfWork ofWork;
public RoleController(UnitOfWork unitOfWork) : base(unitOfWork)
{
this.ofWork = unitOfWork;
}
[HttpGet]
public JsonResult List(SysRole model, PageInfo pageInfo)
{
Expression<Func<SysRole, bool>> expression = t => t.Id != "";
if (!string.IsNullOrEmpty(model.Name))
{
expression = MyLambda.And(expression, t => t.Name.Contains(model.Name));
}
var result = ofWork.SysRoleRepository.GetPage(expression, pageInfo.page, pageInfo.limit, "SortCode");
var list = result?.data.Select(s => new
{
CreateTime = (s.CreateTime == null ? default(DateTime) : s.CreateTime.Value).ToString("yyyy-MM-dd HH:mm"),
s.Code,
s.Name,
s.Id,
s.SortCode
}).ToList();
return Json(Pager.Paging(list, result.total));
}
public IActionResult Add()
{
return View();
}
[HttpPost]
public IActionResult Add(SysRole model)
{
model.Id = Guid.NewGuid().ToString();
model.CreateTime = DateTime.Now;
var result = ofWork.SysRoleRepository.Insert(model) ? SuccessTip("添加成功") : ErrorTip("添加失败");
return Json(result);
}
public IActionResult Edit(string id)
{
var model = ofWork.SysRoleRepository.Get(id);
return View(model);
}
[HttpPost]
public IActionResult Edit(SysRole model)
{
var result = ofWork.SysRoleRepository.Update(model) ? SuccessTip("修改成功") : ErrorTip("修改失败");
return Json(result);
}
[HttpGet]
public JsonResult Delete(string id)
{
var result = ofWork.SysRoleRepository.Delete(t => t.Id == id) ? SuccessTip("删除成功") : ErrorTip("删除失败");
return Json(result);
}
public IActionResult Assign(string id)
{
ViewBag.RoleId = id;
return View();
}
public IActionResult SetSrc(string id)
{
ViewBag.RoleId = id;
return View();
}
[HttpPost]
public IActionResult InsertBatch(List<SysRoleAuth> list, string roleId)
{
//先删除全部权限
ofWork.SysRoleAuthRepository.Delete(t => t.RoleId == roleId, false);
list.ForEach(s => { s.Id = Guid.NewGuid().ToString(); });
var result = ofWork.SysRoleAuthRepository.Insert(list, true) ? SuccessTip("保存成功") : ErrorTip("保存失败");
return Json(result);
}
}
}
\ No newline at end of file
using ApiCommon;
using ApiModel.Basic;
using ApiModel.Entity;
using ApiSys.Common;
using ApiSys.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
namespace ApiSys.Controllers
{
public class UserRegController : BaseController
{
protected WebInfo webInfo;
public UserRegController(UnitOfWork unitOfWork, WebInfo info) : base(unitOfWork)
{
this.webInfo = info;
}
public SelectList OrganizeList
{
get
{
return new SelectList(ofWork.SysOrgRepository
.GetList(t => t.Id != Guid.Empty.ToString())
.Select(s => new
{
s.Id,
s.Name
}), "Id", "Name");
}
}
public SelectList RoleList
{
get
{
return new SelectList(ofWork.SysRoleRepository
.GetList()
.Select(s => new
{
s.Id,
s.Name
}), "Id", "Name");
}
}
[HttpGet]
public JsonResult List(SysUser model, PageInfo pageInfo)
{
Expression<Func<SysUser, bool>> expression = t => (t.IsApprove == "未审核" || t.IsApprove == "审核中" || t.IsApprove == "已驳回");
if (!string.IsNullOrEmpty(model.Name))
{
expression = MyLambda.And(expression, t => t.Name.Contains(model.Name));
}
if (!string.IsNullOrEmpty(model.Account))
{
expression = MyLambda.And(expression, t => t.Account.Contains(model.Account));
}
var result = ofWork.SysUserRepository.GetPage(expression, pageInfo.page, pageInfo.limit, "CreateTime", false, new string[] { "Role", "Dept" });
var list = result?.data.Select(s => new
{
s.Account,
s.Id,
s.Name,
s.DeptId,
DeptName = s.Dept?.Name,
RoleName = s.Role?.Name,
s.RoleId,
CreateTime = s.CreateTime.Value.ToString("yyyy-MM-dd HH:mm"),
s.Isdel,
s.IsLock,
s.IsApprove
}).ToList();
return Json(Pager.Paging(list, result.total));
}
public ActionResult Approve(string id)
{
ViewBag.UserId = id;
ViewBag.UploadFileSize = webInfo.UploadSize;
ViewBag.OrganizeList = OrganizeList;
ViewBag.RoleList = RoleList;
var model = ofWork.SysUserRepository.Get(id);
return View(model);
}
[HttpPost]
public ActionResult Approve(SysUser model)
{
if (model.IsApprove=="已审核")
{
model.ApproveText = "已审核";
model.ApproveTime = DateTime.Now;
model.RoleId = webInfo.PassRole;
model.DeptId = webInfo.RegDepart;
var result = ofWork.SysUserRepository.Update(model, true) ? SuccessTip("审批成功") : ErrorTip("审批失败");
return Json(result);
}
else
{
Expression<Func<SysUser, object>>[] updatedProperties = { p => p.IsApprove, p => p.ApproveText };
model.ApproveText = "审批未通过,请检查用户信息";
var result = ofWork.SysUserRepository.Update(model, updatedProperties, true) ? SuccessTip("申请已驳回") : ErrorTip("申请驳回失败");
return Json(result);
}
}
[HttpPost]
public IActionResult SetOrg(List<SysUserApiOrg> list, string userId)
{
//先删除全部权限
ofWork.SysUserApiOrgRepository.Delete(t => t.UserId == userId, false);
list.ForEach(s => { s.Id = Guid.NewGuid().ToString(); });
var result = ofWork.SysUserApiOrgRepository.Insert(list, true) ? SuccessTip("保存成功") : ErrorTip("保存失败");
return Json(result);
}
[HttpPost]
public JsonResult GetUserOrgs(string userId)
{
var rights = ofWork.SysUserApiOrgRepository.GetList(t => t.UserId == userId).ToList().Select(s => s.OrgId).ToList();
var lefts = ofWork.ApiOrgRepository.GetList().ToList().Select(x => new
{
value = x.Id,
title = x.Name
});
return Json(new AjaxResult
{
data = new
{
left = lefts,
right = rights
},
message = "",
state = ResultType.success.ToString()
});
}
}
}
\ No newline at end of file
#See https://aka.ms/containerfastmode to understand how Visual Studio uses this Dockerfile to build your images for faster debugging.
#Depending on the operating system of the host machines(s) that will build or run the containers, the image specified in the FROM statement may need to be changed.
#For more information, please see https://aka.ms/containercompat
FROM mcr.microsoft.com/dotnet/core/aspnet:3.1 AS base
WORKDIR /app
EXPOSE 80
EXPOSE 443
FROM mcr.microsoft.com/dotnet/core/sdk:3.1 AS build
WORKDIR /src
COPY ["ApiSys/ApiSys.csproj", "ApiSys/"]
RUN dotnet restore "ApiSys/ApiSys.csproj"
COPY . .
WORKDIR "/src/ApiSys"
RUN dotnet build "ApiSys.csproj" -c Release -o /app/build
FROM build AS publish
RUN dotnet publish "ApiSys.csproj" -c Release -o /app/publish
FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "ApiSys.dll"]
\ No newline at end of file
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
using ApiCommon;
using ApiModel.Basic;
using ApiModel.Entity;
using ApiSys.Models;
namespace ApiSys.Extensions
{
public static class LinqExtensions
{
public static IEnumerable<TSource> DistinctBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
{
HashSet<TKey> seenKeys = new HashSet<TKey>();
foreach (TSource element in source)
{
if (seenKeys.Add(keySelector(element)))
{
yield return element;
}
}
}
}
}
using System;
using System.IO;
using System.Text;
using ApiModel.Entity;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using MQTTnet;
using MQTTnet.Client.Receiving;
using MQTTnet.Protocol;
using MQTTnet.Server;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace ApiSys.Extensions
{
public class MQTTServer : IDisposable
{
public MqttServer mqttServer { get; set; }
private ApiSysContext context;
public MQTTServer(string connection)
{
var options = new DbContextOptionsBuilder<ApiSysContext>();
options.UseSqlServer(connection);
context = new ApiSysContext(options.Options);
}
public async void StartMqttServer(IConfiguration configuration)
{
try
{
if (mqttServer == null)
{
var optionsBuilder = new MqttServerOptionsBuilder()
.WithDefaultEndpoint()
.WithDefaultEndpointPort(int.Parse(configuration.GetSection("MQTT:Port").Value))
.WithConnectionValidator(
c =>
{
var currentUser = configuration["MQTT:UserName"].ToString();
var currentPWD = configuration["MQTT:Password"].ToString();
if (string.IsNullOrEmpty(currentUser) || string.IsNullOrEmpty(currentPWD))
{
c.ReasonCode = MqttConnectReasonCode.BadUserNameOrPassword;
return;
}
if (c.Username != currentUser)
{
c.ReasonCode = MqttConnectReasonCode.BadUserNameOrPassword;
return;
}
if (c.Password != currentPWD)
{
c.ReasonCode = MqttConnectReasonCode.BadUserNameOrPassword;
return;
}
c.ReasonCode = MqttConnectReasonCode.Success;
})
.WithSubscriptionInterceptor(
c =>
{
c.AcceptSubscription = true;
})
.WithApplicationMessageInterceptor(
c =>
{
c.AcceptPublish = true;
});
mqttServer = new MqttFactory().CreateMqttServer() as MqttServer;
mqttServer.StartedHandler = new MqttServerStartedHandlerDelegate(OnMqttServerStarted);
mqttServer.StoppedHandler = new MqttServerStoppedHandlerDelegate(OnMqttServerStopped);
mqttServer.ClientConnectedHandler = new MqttServerClientConnectedHandlerDelegate(OnMqttServerClientConnected);
mqttServer.ClientDisconnectedHandler = new MqttServerClientDisconnectedHandlerDelegate(OnMqttServerClientDisconnected);
mqttServer.ClientSubscribedTopicHandler = new MqttServerClientSubscribedTopicHandlerDelegate(OnMqttServerClientSubscribedTopic);
mqttServer.ClientUnsubscribedTopicHandler = new MqttServerClientUnsubscribedTopicHandlerDelegate(OnMqttServerClientUnsubscribedTopic);
mqttServer.ApplicationMessageReceivedHandler = new MqttApplicationMessageReceivedHandlerDelegate(OnMqttServer_ApplicationMessageReceived);
await mqttServer.StartAsync(optionsBuilder.Build());
//lbxMonitor.BeginInvoke(_updateMonitorAction,
// Logger.TraceLog(Logger.Level.Info, "MQTT Server is started."));
}
}
catch (Exception ex)
{
//lbxMonitor.BeginInvoke(_updateMonitorAction,
// Logger.TraceLog(Logger.Level.Fatal, $"MQTT Server start fail.>{ex.Message}"));
}
}
public async void StopMqttServer()
{
if (mqttServer == null) return;
try
{
await mqttServer?.StopAsync();
mqttServer = null;
//lbxMonitor.BeginInvoke(_updateMonitorAction,
// Logger.TraceLog(Logger.Level.Info, "MQTT Server is stopped."));
}
catch (Exception ex)
{
//lbxMonitor.BeginInvoke(_updateMonitorAction,
// Logger.TraceLog(Logger.Level.Fatal, $"MQTT Server stop fail.>{ex.Message}"));
}
}
public async void ServerPublishMqttTopic(string topic, string payload)
{
var message = new MqttApplicationMessage()
{
Topic = topic,
Payload = Encoding.UTF8.GetBytes(payload)
};
await mqttServer.PublishAsync(message);
//lbxMonitor.BeginInvoke(_updateMonitorAction,
// Logger.TraceLog(Logger.Level.Info, string.Format("MQTT Broker发布主题[{0}]成功!", topic)));
}
public void OnMqttServerStarted(EventArgs e)
{
//Console.WriteLine("MQTT服务启动完成!");
}
public void OnMqttServerStopped(EventArgs e)
{
//Console.WriteLine("MQTT服务停止完成!");
}
public void OnMqttServerClientConnected(MqttServerClientConnectedEventArgs e)
{
context.ApiMqttMessages.Add(new ApiMqttMessage
{
Id = Guid.NewGuid().ToString(),
CreateTime = DateTime.Now,
DeviceNo = e.ClientId,
DeviceType = e.ClientId.Substring(0, 2),
Topic = "Connected",
Payload = $"客户端[{e.ClientId}]已连接"
});
context.SaveChanges();
//Console.WriteLine($"客户端[{e.ClientId}]已连接");
}
public void OnMqttServerClientDisconnected(MqttServerClientDisconnectedEventArgs e)
{
context.ApiMqttMessages.Add(new ApiMqttMessage
{
Id = Guid.NewGuid().ToString(),
CreateTime = DateTime.Now,
DeviceNo = e.ClientId,
DeviceType = e.ClientId.Substring(0, 2),
Topic = "Disconnected",
Payload = $"客户端[{e.ClientId}]已断开连接!"
});
context.SaveChanges();
//Console.WriteLine($"客户端[{e.ClientId}]已断开连接!");
}
public void OnMqttServerClientSubscribedTopic(MqttServerClientSubscribedTopicEventArgs e)
{
//Console.WriteLine($"客户端[{e.ClientId}]已成功订阅主题[{e.TopicFilter}]!");
}
public void OnMqttServerClientUnsubscribedTopic(MqttServerClientUnsubscribedTopicEventArgs e)
{
//Console.WriteLine($"客户端[{e.ClientId}]已成功取消订阅主题[{e.TopicFilter}]!");
}
public void OnMqttServer_ApplicationMessageReceived(MqttApplicationMessageReceivedEventArgs e)
{
context.ApiMqttMessages.Add(new ApiMqttMessage
{
Id = Guid.NewGuid().ToString(),
CreateTime = DateTime.Now,
DeviceNo = e.ClientId,
DeviceType = e.ClientId.Substring(0, 2),
Topic = e.ApplicationMessage.Topic,
Payload = Encoding.UTF8.GetString(e.ApplicationMessage.Payload)
});
context.SaveChanges();
//Console.WriteLine($"客户端[{e.ClientId}]>> 主题:{e.ApplicationMessage.Topic} 负荷:{Encoding.UTF8.GetString(e.ApplicationMessage.Payload)} Qos:{e.ApplicationMessage.QualityOfServiceLevel} 保留:{e.ApplicationMessage.Retain}");
}
public void Dispose()
{
StopMqttServer();
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace ApiSys.Models
{
public class AuthModel
{
public string appKey { get; set; }
public string apiName { get; set; }
public string orgId { get; set; }
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace ApiSys.Models
{
public class CabinetModel
{
public string Id { get; set; }
public int count { get; set; }
public string CabinetNum { get; set; }
public string CabinetRealNum { get; set; }
public string OrganizationId { get; set; }
public string Name { get; set; }
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace ApiSys.Models
{
public class ChannelCfgModel
{
public string id { get; set; }
public string location { get; set; }
public string name { get; set; }
public bool state { get; set; }
public string orgName { get; set; }
public string orgId { get; set; }
public string createTime { get; set; }
public string warehouseId { get; set; }
public string warehouseName { get; set; }
public string updateUser { get; set; }
public string code { get; set; }
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace ApiSys.Models
{
public class DocIns
{
public string DemoText { get; set; }
public string ApiName { get; set; }
public string ApiType { get; set; }
public string ApiUrl { get; set; }
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace ApiSys.Models
{
public class JunmpPoliceStationBaseModel<T>
{
public string code { get; set; }
public string msg { get; set; }
public T data { get; set; }
}
public class PagedListModel<T>
{
public int totalElements { get; set; }
public List<T> content { get; set; }
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace ApiSys.Models
{
public class MQTTLogSearchModel
{
/// <summary>
/// 设备类型
/// </summary>
public string Type { get; set; }
/// <summary>
/// 组织机构
/// </summary>
public string OrganizationId { get; set; }
/// <summary>
/// 设备状态
/// </summary>
public string Status { get; set; }
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace ApiSys.Models
{
public class ModuleTree
{
public string id { get; set; }
public string title { get; set; }
public string href { get; set; }
public string fontFamily { get; set; }
public string icon { get; set; }
public IEnumerable<ModuleTree> children { get; set; }
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace ApiSys.Models
{
public class PageInfo
{
//当前页码
public int page { get; set; }
//每页数据量
public int limit { get; set; }
}
}
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace ApiSys.Models
{
/// <summary>
/// 显示位置枚举
/// </summary>
public enum PositionEnum
{
/// <summary>
/// 表内
/// </summary>
[Display(Name = "表内")]
FormInside = 0,
/// <summary>
/// 表外
/// </summary>
[Display(Name = "表外")]
FormRightTop = 1
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Xml.Serialization;
namespace ApiSys.Models
{
public class SwgJson
{
public string demo { get; set; }
public string type { get; set; }
public string url { get; set; }
public string name { get; set; }
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace ApiSys.Models
{
public class TreeSelect
{
public string id { get; set; }
public string name { get; set; }
public bool open { get; set; }
public List<TreeSelect> children { get; set; }
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace ApiSys.Models
{
public class UiTreeNode
{
public bool isOpen { get; set; }
public string label { get; set; }
public string id { get; set; }
public bool @checked { get; set; }
public List<UiTreeNode> children { get; set; }
}
}
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace ApiSys
{
public class Program
{
public static void Main(string[] args)
{
try
{
CreateHostBuilder(args).Build().Run();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
public static IWebHostBuilder CreateHostBuilder(string[] args)
{
var configuration = new ConfigurationBuilder().SetBasePath(AppContext.BaseDirectory)
.AddJsonFile(AppContext.BaseDirectory + "appsettings.json").Build();
return WebHost.CreateDefaultBuilder(args)
.UseUrls(configuration["Launch"]).UseStartup<Startup>();
}
}
}
{
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:51745",
"sslPort": 0
}
},
"profiles": {
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"ApiSys": {
"commandName": "Project",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
},
"applicationUrl": "http://localhost:5001;http://192.168.3.74:5001;"
},
"Docker": {
"commandName": "Docker",
"launchBrowser": true,
"launchUrl": "{Scheme}://{ServiceHost}:{ServicePort}",
"publishAllPorts": true,
"useSSL": true
}
}
}
\ No newline at end of file
using ApiModel.Basic;
using ApiModel.Entity;
using ApiSys.Common;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.StaticFiles;
using Microsoft.DotNet.PlatformAbstractions;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.WebEncoders;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text.Encodings.Web;
using System.Text.Unicode;
using System.Threading.Tasks;
using ApiSys.Extensions;
namespace ApiSys
{
public class Startup
{
public const string CookieScheme = "Cookies";
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.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
var connection = Configuration.GetConnectionString("ConnectionStr");
//读取网站配置并注入
WebInfo webInfo = new WebInfo();
//注入验证码策略
services.AddSingleton<IVerCodePolicy, VerCodePolicy>();
services.Configure<WebInfo>(Configuration.GetSection("WebInfo"));
Configuration.GetSection("WebInfo").Bind(webInfo);
services.AddSingleton(webInfo);
services.AddRazorPages().AddRazorRuntimeCompilation();
services.AddTransient(typeof(UnitOfWork));//注入工作单元
//配置跨域处理,允许所有来源
services.AddCors(options =>
{
options.AddPolicy("cors",
builder => builder.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod()
);
});
services.Configure<FormOptions>(x =>
{
x.ValueLengthLimit = int.MaxValue;
x.MultipartBodyLengthLimit = int.MaxValue;
x.MultipartHeadersLengthLimit = int.MaxValue;
});
//添加NACOS配置
services.AddNacosNaming(Configuration)
.AddNacosConfig(Configuration)
.AddNacosAspNetCore(Configuration);
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.Configure<WebEncoderOptions>(options =>
{
options.TextEncoderSettings = new TextEncoderSettings(UnicodeRanges.All);
});
services.AddHttpClient();
services.AddControllersWithViews().AddNewtonsoftJson();
services.AddDbContext<ApiSysContext>(options =>
{
options.UseSqlServer(connection);
});
#region 身份认证
services.AddSession(options =>
{
options.Cookie.HttpOnly = true;
options.Cookie.SecurePolicy = CookieSecurePolicy.SameAsRequest;
options.IdleTimeout = TimeSpan.FromMinutes(60);
});
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options =>
{
options.DataProtectionProvider = DataProtectionProvider.Create(new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory + "/shared-auth-ticket-keys/"));
options.Cookie.Path = "/";
options.LoginPath = new PathString("/Login/Index");
options.AccessDeniedPath = new PathString("/Forbidden"); //禁止访问路径:当用户试图访问资源时,但未通过该资源的任何授权策略,请求将被重定向到这个相对路径。
// options.SlidingExpiration = false; //Cookie可以分为永久性的和临时性的。 临时性的是指只在当前浏览器进程里有效,浏览器一旦关闭就失效(被浏览器删除)。 永久性的是指Cookie指定了一个过期时间,在这个时间到达之前,此cookie一直有效(浏览器一直记录着此cookie的存在)。 slidingExpriation的作用是,指示浏览器把cookie作为永久性cookie存储,但是会自动更改过期时间,以使用户不会在登录后并一直活动,但是一段时间后却自动注销。也就是说,你10点登录了,服务器端设置的TimeOut为30分钟,如果slidingExpriation为false,那么10:30以后,你就必须重新登录。如果为true的话,你10:16分时打开了一个新页面,服务器就会通知浏览器,把过期时间修改为10:46。 更详细的说明还是参考MSDN的文档。
});
#endregion
services.AddSession();
////启动MQTT
//var mqtt = new MQTTServer(connection);
//mqtt.StartMqttServer(Configuration);
//services.AddSingleton(mqtt);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseSession();
app.UseCookiePolicy();
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
//允许所有跨域,cors是在ConfigureServices方法中配置的跨域策略名称
//注意:UseCors必须放在UseRouting和UseEndpoints之间
app.UseCors("cors");
app.UseAuthentication();
app.UseEndpoints(endpoints =>
{
endpoints.MapDefaultControllerRoute();
endpoints.MapRazorPages();
});
app.UseStaticFiles(new StaticFileOptions()
{
ContentTypeProvider = new FileExtensionContentTypeProvider()
{
Mappings = { [".exe"] = "application/octect-stream", [".apk"] = "application/octect-stream", [".log"] = "text/plain", [".mp4"] = " video/mpeg4" }
}
});
}
}
}
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论