sync with OpenAuth.Core

This commit is contained in:
yubaolee 2020-12-27 00:00:28 +08:00
parent 368eae8d63
commit 20a717b2e6
19 changed files with 451 additions and 199 deletions

View File

@ -1,4 +1,4 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema; using System.ComponentModel.DataAnnotations.Schema;
@ -14,7 +14,6 @@ namespace Infrastructure.Extensions
{ {
public static class EntityProperties public static class EntityProperties
{ {
public static string GetExpressionPropertyFirst<TEntity>(this Expression<Func<TEntity, object>> properties) public static string GetExpressionPropertyFirst<TEntity>(this Expression<Func<TEntity, object>> properties)
{ {
string[] arr = properties.GetExpressionProperty(); string[] arr = properties.GetExpressionProperty();
@ -22,6 +21,7 @@ namespace Infrastructure.Extensions
return arr[0]; return arr[0];
return ""; return "";
} }
/// <summary> /// <summary>
/// 获取对象里指定成员名称 /// 获取对象里指定成员名称
/// </summary> /// </summary>
@ -33,13 +33,14 @@ namespace Infrastructure.Extensions
if (properties == null) if (properties == null)
return new string[] { }; return new string[] { };
if (properties.Body is NewExpression) if (properties.Body is NewExpression)
return ((NewExpression)properties.Body).Members.Select(x => x.Name).ToArray(); return ((NewExpression) properties.Body).Members.Select(x => x.Name).ToArray();
if (properties.Body is MemberExpression) if (properties.Body is MemberExpression)
return new string[] { ((MemberExpression)properties.Body).Member.Name }; return new string[] {((MemberExpression) properties.Body).Member.Name};
if (properties.Body is UnaryExpression) if (properties.Body is UnaryExpression)
return new string[] { ((properties.Body as UnaryExpression).Operand as MemberExpression).Member.Name }; return new string[] {((properties.Body as UnaryExpression).Operand as MemberExpression).Member.Name};
throw new Exception("未实现的表达式"); throw new Exception("未实现的表达式");
} }
public static string ValidateHashInEntity(this Type typeinfo, Dictionary<string, object> dic) public static string ValidateHashInEntity(this Type typeinfo, Dictionary<string, object> dic)
{ {
return typeinfo.ValidateDicInEntity(dic, false); return typeinfo.ValidateDicInEntity(dic, false);
@ -47,7 +48,6 @@ namespace Infrastructure.Extensions
public static void RemoveNotExistColumns(this Type typeinfo, List<string> cols) public static void RemoveNotExistColumns(this Type typeinfo, List<string> cols)
{ {
} }
/// <summary> /// <summary>
@ -59,14 +59,16 @@ namespace Infrastructure.Extensions
{ {
return typeinfo.GetProperties().Select(c => c.Name).ToList(); return typeinfo.GetProperties().Select(c => c.Name).ToList();
} }
public static void IsExistColumns(this Type typeinfo) public static void IsExistColumns(this Type typeinfo)
{ {
} }
public static Dictionary<string, string> GetColumType(this PropertyInfo[] properties) public static Dictionary<string, string> GetColumType(this PropertyInfo[] properties)
{ {
return properties.GetColumType(false); return properties.GetColumType(false);
} }
public static Dictionary<string, string> GetColumType(this PropertyInfo[] properties, bool containsKey) public static Dictionary<string, string> GetColumType(this PropertyInfo[] properties, bool containsKey)
{ {
Dictionary<string, string> dictionary = new Dictionary<string, string>(); Dictionary<string, string> dictionary = new Dictionary<string, string>();
@ -76,29 +78,33 @@ namespace Infrastructure.Extensions
{ {
continue; continue;
} }
var keyVal = GetColumnType(property, true); var keyVal = GetColumnType(property, true);
dictionary.Add(keyVal.Key, keyVal.Value); dictionary.Add(keyVal.Key, keyVal.Value);
} }
return dictionary; return dictionary;
} }
private static readonly Dictionary<Type, string> entityMapDbColumnType = new Dictionary<Type, string>() { private static readonly Dictionary<Type, string> entityMapDbColumnType = new Dictionary<Type, string>()
{typeof(int),SqlDbTypeName.Int }, {
{typeof(int?),SqlDbTypeName.Int }, {typeof(int), SqlDbTypeName.Int},
{typeof(long),SqlDbTypeName.BigInt }, {typeof(int?), SqlDbTypeName.Int},
{typeof(long?),SqlDbTypeName.BigInt }, {typeof(long), SqlDbTypeName.BigInt},
{typeof(decimal),"decimal(18, 5)" }, {typeof(long?), SqlDbTypeName.BigInt},
{typeof(decimal?),"decimal(18, 5)" }, {typeof(decimal), "decimal(18, 5)"},
{typeof(double),"decimal(18, 5)" }, {typeof(decimal?), "decimal(18, 5)"},
{typeof(double?),"decimal(18, 5)" }, {typeof(double), "decimal(18, 5)"},
{typeof(float),"decimal(18, 5)" }, {typeof(double?), "decimal(18, 5)"},
{typeof(float?),"decimal(18, 5)" }, {typeof(float), "decimal(18, 5)"},
{typeof(Guid),"UniqueIdentifier" }, {typeof(float?), "decimal(18, 5)"},
{typeof(Guid?),"UniqueIdentifier" }, {typeof(Guid), "UniqueIdentifier"},
{typeof(byte),"tinyint" }, {typeof(Guid?), "UniqueIdentifier"},
{typeof(byte?),"tinyint" }, {typeof(byte), "tinyint"},
{typeof(string),"nvarchar" } {typeof(byte?), "tinyint"},
{typeof(string), "nvarchar"}
}; };
/// <summary> /// <summary>
/// 返回属性的字段及数据库类型 /// 返回属性的字段及数据库类型
/// </summary> /// </summary>
@ -111,7 +117,7 @@ namespace Infrastructure.Extensions
object objAtrr = property.GetTypeCustomAttributes(typeof(ColumnAttribute), out bool asType); object objAtrr = property.GetTypeCustomAttributes(typeof(ColumnAttribute), out bool asType);
if (asType) if (asType)
{ {
colType = ((ColumnAttribute)objAtrr).TypeName.ToLower(); colType = ((ColumnAttribute) objAtrr).TypeName.ToLower();
if (!string.IsNullOrEmpty(colType)) if (!string.IsNullOrEmpty(colType))
{ {
//不需要具体长度直接返回 //不需要具体长度直接返回
@ -119,12 +125,13 @@ namespace Infrastructure.Extensions
{ {
return new KeyValuePair<string, string>(property.Name, colType); return new KeyValuePair<string, string>(property.Name, colType);
} }
if (colType == "decimal" || colType == "double" || colType == "float") if (colType == "decimal" || colType == "double" || colType == "float")
{ {
objAtrr = property.GetTypeCustomAttributes(typeof(DisplayFormatAttribute), out asType); objAtrr = property.GetTypeCustomAttributes(typeof(DisplayFormatAttribute), out asType);
colType += "(" + (asType ? ((DisplayFormatAttribute)objAtrr).DataFormatString : "18,5") + ")"; colType += "(" + (asType ? ((DisplayFormatAttribute) objAtrr).DataFormatString : "18,5") + ")";
} }
///如果是string,根据 varchar或nvarchar判断最大长度 ///如果是string,根据 varchar或nvarchar判断最大长度
if (property.PropertyType.ToString() == "System.String") if (property.PropertyType.ToString() == "System.String")
{ {
@ -132,17 +139,21 @@ namespace Infrastructure.Extensions
objAtrr = property.GetTypeCustomAttributes(typeof(MaxLengthAttribute), out asType); objAtrr = property.GetTypeCustomAttributes(typeof(MaxLengthAttribute), out asType);
if (asType) if (asType)
{ {
int length = ((MaxLengthAttribute)objAtrr).Length; int length = ((MaxLengthAttribute) objAtrr).Length;
colType += "(" + (length < 1 || length > (colType.StartsWith("n") ? 8000 : 4000) ? "max" : length.ToString()) + ")"; colType += "(" + (length < 1 || length > (colType.StartsWith("n") ? 8000 : 4000)
? "max"
: length.ToString()) + ")";
} }
else else
{ {
colType += "(max)"; colType += "(max)";
} }
} }
return new KeyValuePair<string, string>(property.Name, colType); return new KeyValuePair<string, string>(property.Name, colType);
} }
} }
if (entityMapDbColumnType.TryGetValue(property.PropertyType, out string value)) if (entityMapDbColumnType.TryGetValue(property.PropertyType, out string value))
{ {
colType = value; colType = value;
@ -151,10 +162,12 @@ namespace Infrastructure.Extensions
{ {
colType = SqlDbTypeName.NVarChar; colType = SqlDbTypeName.NVarChar;
} }
if (lenght && colType == SqlDbTypeName.NVarChar) if (lenght && colType == SqlDbTypeName.NVarChar)
{ {
colType = "nvarchar(max)"; colType = "nvarchar(max)";
} }
return new KeyValuePair<string, string>(property.Name, colType); return new KeyValuePair<string, string>(property.Name, colType);
} }
@ -171,10 +184,12 @@ namespace Infrastructure.Extensions
{ {
return string.Empty; return string.Empty;
} }
string columnType = string.Empty; string columnType = string.Empty;
List<ArrayEntity> arrrayEntityList = array.Select(x => new ArrayEntity { column1 = x.ToString() }).ToList(); List<ArrayEntity> arrrayEntityList = array.Select(x => new ArrayEntity {column1 = x.ToString()}).ToList();
return arrrayEntityList.GetEntitySql(false, null, null, null, fieldType); return arrrayEntityList.GetEntitySql(false, null, null, null, fieldType);
} }
/// <summary> /// <summary>
///<param name="sql">要执行的sql语句如通过EntityToSqlTempName.Temp_Insert0.ToString()字符串占位生成的的sql语句会把EntityToSqlTempName.Temp_Insert0.ToString()替换成生成的sql临时表数据 ///<param name="sql">要执行的sql语句如通过EntityToSqlTempName.Temp_Insert0.ToString()字符串占位生成的的sql语句会把EntityToSqlTempName.Temp_Insert0.ToString()替换成生成的sql临时表数据
/// string sql = " ;DELETE FROM " + typeEntity.Name + " where " + typeEntity.GetKeyName() + /// string sql = " ;DELETE FROM " + typeEntity.Name + " where " + typeEntity.GetKeyName() +
@ -191,14 +206,17 @@ namespace Infrastructure.Extensions
{ {
return string.Empty; return string.Empty;
} }
string columnType = string.Empty; string columnType = string.Empty;
List<ArrayEntity> arrrayEntityList = array.Select(x => new ArrayEntity { column1 = x.ToString() }).ToList(); List<ArrayEntity> arrrayEntityList = array.Select(x => new ArrayEntity {column1 = x.ToString()}).ToList();
return arrrayEntityList.GetEntitySql(false, sql, null, null, fieldType); return arrrayEntityList.GetEntitySql(false, sql, null, null, fieldType);
} }
public static string GetArraySql<T>(this object[] array, string sql) public static string GetArraySql<T>(this object[] array, string sql)
{ {
return array.GetArraySql(typeof(T).GetFieldType(), sql); return array.GetArraySql(typeof(T).GetFieldType(), sql);
} }
/// <summary> /// <summary>
/// 根据实体获取key的类型用于update或del操作 /// 根据实体获取key的类型用于update或del操作
/// </summary> /// </summary>
@ -207,17 +225,30 @@ namespace Infrastructure.Extensions
public static FieldType GetFieldType(this Type typeEntity) public static FieldType GetFieldType(this Type typeEntity)
{ {
FieldType fieldType; FieldType fieldType;
string columnType = typeEntity.GetProperties().Where(x => x.Name == typeEntity.GetKeyName()).ToList()[0].GetColumnType(false).Value; string columnType = typeEntity.GetProperties().Where(x => x.Name == typeEntity.GetKeyName()).ToList()[0]
.GetColumnType(false).Value;
switch (columnType) switch (columnType)
{ {
case SqlDbTypeName.Int: fieldType = FieldType.Int; break; case SqlDbTypeName.Int:
case SqlDbTypeName.BigInt: fieldType = FieldType.BigInt; break; fieldType = FieldType.Int;
case SqlDbTypeName.VarChar: fieldType = FieldType.VarChar; break; break;
case SqlDbTypeName.UniqueIdentifier: fieldType = FieldType.UniqueIdentifier; break; case SqlDbTypeName.BigInt:
default: fieldType = FieldType.NvarChar; break; fieldType = FieldType.BigInt;
break;
case SqlDbTypeName.VarChar:
fieldType = FieldType.VarChar;
break;
case SqlDbTypeName.UniqueIdentifier:
fieldType = FieldType.UniqueIdentifier;
break;
default:
fieldType = FieldType.NvarChar;
break;
} }
return fieldType; return fieldType;
} }
public static string GetEntitySql<T>(this IEnumerable<T> entityList, public static string GetEntitySql<T>(this IEnumerable<T> entityList,
bool containsKey = false, bool containsKey = false,
string sql = null, string sql = null,
@ -226,13 +257,13 @@ namespace Infrastructure.Extensions
FieldType? fieldType = null FieldType? fieldType = null
) )
{ {
if (entityList == null || entityList.Count() == 0) return ""; if (entityList == null || entityList.Count() == 0) return "";
PropertyInfo[] propertyInfo = typeof(T).GetProperties().ToArray(); PropertyInfo[] propertyInfo = typeof(T).GetProperties().ToArray();
if (propertyInfo.Count() == 0) if (propertyInfo.Count() == 0)
{ {
propertyInfo = entityList.ToArray()[0].GetType().GetGenericProperties().ToArray(); propertyInfo = entityList.ToArray()[0].GetType().GetGenericProperties().ToArray();
} }
propertyInfo = propertyInfo.GetGenericProperties().ToArray(); propertyInfo = propertyInfo.GetGenericProperties().ToArray();
string[] arr = null; string[] arr = null;
@ -240,8 +271,10 @@ namespace Infrastructure.Extensions
{ {
arr = fixedColumns.GetExpressionToArray(); arr = fixedColumns.GetExpressionToArray();
PropertyInfo keyProperty = typeof(T).GetKeyProperty(); PropertyInfo keyProperty = typeof(T).GetKeyProperty();
propertyInfo = propertyInfo.Where(x => (containsKey && x.Name == keyProperty.Name) || arr.Contains(x.Name)).ToArray(); propertyInfo = propertyInfo
.Where(x => (containsKey && x.Name == keyProperty.Name) || arr.Contains(x.Name)).ToArray();
} }
if (ignoreFileds != null) if (ignoreFileds != null)
{ {
arr = ignoreFileds.GetExpressionToArray(); arr = ignoreFileds.GetExpressionToArray();
@ -252,12 +285,15 @@ namespace Infrastructure.Extensions
if (fieldType != null) if (fieldType != null)
{ {
string realType = fieldType.ToString(); string realType = fieldType.ToString();
if ((int)fieldType == 0 || (int)fieldType == 1) if ((int) fieldType == 0 || (int) fieldType == 1)
{ {
realType += "(max)"; realType += "(max)";
} }
dictProperties = new Dictionary<string, string> { { dictProperties.Select(x => x.Key).ToList()[0], realType } };
dictProperties = new Dictionary<string, string>
{{dictProperties.Select(x => x.Key).ToList()[0], realType}};
} }
if (dictProperties.Keys.Count * entityList.Count() > 50 * 3000) if (dictProperties.Keys.Count * entityList.Count() > 50 * 3000)
{ {
throw new Exception("写入数据太多,请分开写入。"); throw new Exception("写入数据太多,请分开写入。");
@ -299,19 +335,27 @@ namespace Infrastructure.Extensions
stringCenter.Remove(stringCenter.Length - 1, 1).Append("',").ToString() + stringCenter.Remove(stringCenter.Length - 1, 1).Append("',").ToString() +
stringRight.Remove(stringRight.Length - 1, 1).ToString()); stringRight.Remove(stringRight.Length - 1, 1).ToString());
stringLeft.Clear(); stringCenter.Clear(); stringRight.Clear(); stringLeft.Clear();
stringCenter.Clear();
stringRight.Clear();
} }
stringLeft.AppendLine("exec sp_executesql N'SET NOCOUNT ON;"); stringLeft.AppendLine("exec sp_executesql N'SET NOCOUNT ON;");
stringCenter.Append("N'"); stringCenter.Append("N'");
index = 0; count = 0; index = 0;
count = 0;
} }
stringLeft.Append(index == 0 ? "; INSERT INTO " + tempTablbe + " values (" : " "); stringLeft.Append(index == 0 ? "; INSERT INTO " + tempTablbe + " values (" : " ");
index++; index++;
foreach (PropertyInfo property in propertyInfo) foreach (PropertyInfo property in propertyInfo)
{ {
if (!containsKey && property.IsKey()) { continue; } if (!containsKey && property.IsKey())
{
continue;
}
string par = "@v" + count; string par = "@v" + count;
stringLeft.Append(par + ","); stringLeft.Append(par + ",");
stringCenter.Append(par + " " + dictProperties[property.Name] + ","); stringCenter.Append(par + " " + dictProperties[property.Name] + ",");
@ -324,8 +368,10 @@ namespace Infrastructure.Extensions
{ {
stringRight.Append(par + "='" + val.ToString().Replace("'", "''''") + "',"); stringRight.Append(par + "='" + val.ToString().Replace("'", "''''") + "',");
} }
count++; count++;
} }
stringLeft.Remove(stringLeft.Length - 1, 1); stringLeft.Remove(stringLeft.Length - 1, 1);
stringLeft.Append("),("); stringLeft.Append("),(");
} }
@ -337,8 +383,11 @@ namespace Infrastructure.Extensions
stringCenter.Remove(stringCenter.Length - 1, 1).Append("',").ToString() + stringCenter.Remove(stringCenter.Length - 1, 1).Append("',").ToString() +
stringRight.Remove(stringRight.Length - 1, 1).ToString()); stringRight.Remove(stringRight.Length - 1, 1).ToString());
stringLeft.Clear(); stringCenter.Clear(); stringRight.Clear(); stringLeft.Clear();
stringCenter.Clear();
stringRight.Clear();
} }
if (!string.IsNullOrEmpty(sql)) if (!string.IsNullOrEmpty(sql))
{ {
sql = sql.Replace(EntityToSqlTempName.TempInsert.ToString(), tempTablbe); sql = sql.Replace(EntityToSqlTempName.TempInsert.ToString(), tempTablbe);
@ -346,7 +395,9 @@ namespace Infrastructure.Extensions
} }
else else
{ {
declareTable.AppendLine(" SELECT " + (string.Join(",", fixedColumns?.GetExpressionToArray() ?? new string[] { "*" })) + " FROM " + tempTablbe); declareTable.AppendLine(" SELECT " +
(string.Join(",", fixedColumns?.GetExpressionToArray() ?? new string[] {"*"})) +
" FROM " + tempTablbe);
} }
@ -354,6 +405,7 @@ namespace Infrastructure.Extensions
{ {
declareTable.AppendLine("; drop table " + tempTablbe); declareTable.AppendLine("; drop table " + tempTablbe);
} }
return declareTable.ToString(); return declareTable.ToString();
} }
@ -414,14 +466,19 @@ namespace Infrastructure.Extensions
stringCenter.Remove(stringCenter.Length - 1, 1).Append("',").ToString() + stringCenter.Remove(stringCenter.Length - 1, 1).Append("',").ToString() +
stringRight.Remove(stringRight.Length - 1, 1).ToString()); stringRight.Remove(stringRight.Length - 1, 1).ToString());
stringLeft.Clear(); stringCenter.Clear(); stringRight.Clear(); stringLeft.Clear();
stringCenter.Clear();
stringRight.Clear();
} }
// sbLeft.AppendLine(" INSERT INTO @toInsert0"); // sbLeft.AppendLine(" INSERT INTO @toInsert0");
stringLeft.AppendLine("exec sp_executesql N'SET NOCOUNT ON;"); stringLeft.AppendLine("exec sp_executesql N'SET NOCOUNT ON;");
stringCenter.Append("N'"); stringCenter.Append("N'");
index = 0; count = 0; index = 0;
count = 0;
} }
stringLeft.Append(index == 0 ? "; INSERT INTO " + tempTablbe + " values (" : " "); stringLeft.Append(index == 0 ? "; INSERT INTO " + tempTablbe + " values (" : " ");
index++; index++;
foreach (KeyValuePair<string, string> keyValue in dictCloumn) foreach (KeyValuePair<string, string> keyValue in dictCloumn)
@ -438,39 +495,42 @@ namespace Infrastructure.Extensions
{ {
stringRight.Append(par + "='" + val.ToString().Replace("'", "''''") + "',"); stringRight.Append(par + "='" + val.ToString().Replace("'", "''''") + "',");
} }
count++; count++;
} }
stringLeft.Remove(stringLeft.Length - 1, 1); stringLeft.Remove(stringLeft.Length - 1, 1);
stringLeft.Append("),("); stringLeft.Append("),(");
} }
if (stringLeft.Length > 0) if (stringLeft.Length > 0)
{ {
declareTable.AppendLine( declareTable.AppendLine(
stringLeft.Remove(stringLeft.Length - 2, 2).Append("',").ToString() + stringLeft.Remove(stringLeft.Length - 2, 2).Append("',").ToString() +
stringCenter.Remove(stringCenter.Length - 1, 1).Append("',").ToString() + stringCenter.Remove(stringCenter.Length - 1, 1).Append("',").ToString() +
stringRight.Remove(stringRight.Length - 1, 1).ToString()); stringRight.Remove(stringRight.Length - 1, 1).ToString());
stringLeft.Clear(); stringCenter.Clear(); stringRight.Clear(); stringLeft.Clear();
stringCenter.Clear();
stringRight.Clear();
} }
declareTable.AppendLine(" SELECT * FROM " + tempTablbe); declareTable.AppendLine(" SELECT * FROM " + tempTablbe);
if (tempTablbe.Substring(0, 1) == "#") if (tempTablbe.Substring(0, 1) == "#")
{ {
declareTable.AppendLine("; drop table " + tempTablbe); declareTable.AppendLine("; drop table " + tempTablbe);
} }
return declareTable.ToString(); return declareTable.ToString();
} }
public static string GetKeyName(this Type typeinfo) public static string GetKeyName(this Type typeinfo)
{ {
return typeinfo.GetProperties().GetKeyName(); return typeinfo.GetProperties().GetKeyName();
} }
public static string GetKeyType(this Type typeinfo) public static string GetKeyType(this Type typeinfo)
{ {
string keyType = typeinfo.GetProperties().GetKeyName(true); string keyType = typeinfo.GetProperties().GetKeyName(true);
@ -487,10 +547,12 @@ namespace Infrastructure.Extensions
return "nvarchar(max)"; return "nvarchar(max)";
} }
} }
public static string GetKeyName(this PropertyInfo[] properties) public static string GetKeyName(this PropertyInfo[] properties)
{ {
return properties.GetKeyName(false); return properties.GetKeyName(false);
} }
/// <summary> /// <summary>
/// 获取key列名 /// 获取key列名
/// </summary> /// </summary>
@ -509,10 +571,11 @@ namespace Infrastructure.Extensions
var attributes = propertyInfo.GetCustomAttributes(typeof(ColumnAttribute), false); var attributes = propertyInfo.GetCustomAttributes(typeof(ColumnAttribute), false);
//如果没有ColumnAttribute的需要单独再验证下面只验证有属性的 //如果没有ColumnAttribute的需要单独再验证下面只验证有属性的
if (attributes.Length > 0) if (attributes.Length > 0)
return ((ColumnAttribute)attributes[0]).TypeName.ToLower(); return ((ColumnAttribute) attributes[0]).TypeName.ToLower();
else else
return GetColumType(new PropertyInfo[] { propertyInfo }, true)[propertyInfo.Name]; return GetColumType(new PropertyInfo[] {propertyInfo}, true)[propertyInfo.Name];
} }
return keyName; return keyName;
} }
@ -525,10 +588,12 @@ namespace Infrastructure.Extensions
{ {
return entity.GetProperties().GetKeyProperty(); return entity.GetProperties().GetKeyProperty();
} }
public static PropertyInfo GetKeyProperty(this PropertyInfo[] properties) public static PropertyInfo GetKeyProperty(this PropertyInfo[] properties)
{ {
return properties.Where(c => c.IsKey()).FirstOrDefault(); return properties.Where(c => c.IsKey()).FirstOrDefault();
} }
public static bool IsKey(this PropertyInfo propertyInfo) public static bool IsKey(this PropertyInfo propertyInfo)
{ {
object[] keyAttributes = propertyInfo.GetCustomAttributes(typeof(KeyAttribute), false); object[] keyAttributes = propertyInfo.GetCustomAttributes(typeof(KeyAttribute), false);
@ -541,8 +606,6 @@ namespace Infrastructure.Extensions
private static string[] _userEditFields { get; set; } private static string[] _userEditFields { get; set; }
/// <summary> /// <summary>
/// 判断是否包含某个属性: /// 判断是否包含某个属性:
/// 如 [Editable(true)] /// 如 [Editable(true)]
@ -567,6 +630,7 @@ namespace Infrastructure.Extensions
proList.Add(pro); proList.Add(pro);
} }
} }
return proList; return proList;
} }
@ -584,6 +648,7 @@ namespace Infrastructure.Extensions
asType = false; asType = false;
return new string[0]; return new string[0];
} }
asType = true; asType = true;
return attributes[0]; return attributes[0];
} }
@ -595,20 +660,16 @@ namespace Infrastructure.Extensions
/// <param name="entityList"></param> /// <param name="entityList"></param>
/// <param name="expression"></param> /// <param name="expression"></param>
/// <returns></returns> /// <returns></returns>
public static WebResponseContent ValidationEntityList<T>(this List<T> entityList, Expression<Func<T, object>> expression = null) public static void ValidationEntityList<T>(this List<T> entityList,
Expression<Func<T, object>> expression = null)
{ {
WebResponseContent responseData = new WebResponseContent(); WebResponseContent responseData = new WebResponseContent();
foreach (T entity in entityList) foreach (T entity in entityList)
{ {
responseData = entity.ValidationEntity(expression); entity.ValidationEntity(expression);
if (!responseData.Status)
{
return responseData;
} }
} }
responseData.Status = true;
return responseData;
}
/// <summary> /// <summary>
/// 指定需要验证的字段 /// 指定需要验证的字段
/// </summary> /// </summary>
@ -616,10 +677,13 @@ namespace Infrastructure.Extensions
/// <param name="entity"></param> /// <param name="entity"></param>
/// <param name="expression">对指定属性进行验证x=>{x.Name,x.Size}</param> /// <param name="expression">对指定属性进行验证x=>{x.Name,x.Size}</param>
/// <returns></returns> /// <returns></returns>
public static WebResponseContent ValidationEntity<T>(this T entity, Expression<Func<T, object>> expression = null, Expression<Func<T, object>> validateProperties = null) public static void ValidationEntity<T>(this T entity, Expression<Func<T, object>> expression = null,
Expression<Func<T, object>> validateProperties = null)
{ {
return ValidationEntity<T>(entity, expression?.GetExpressionProperty<T>(), validateProperties?.GetExpressionProperty<T>()); ValidationEntity<T>(entity, expression?.GetExpressionProperty<T>(),
validateProperties?.GetExpressionProperty<T>());
} }
/// <summary> /// <summary>
/// specificProperties=null并且validateProperties=null对所有属性验证只验证其是否合法不验证是否为空(除属性标识指定了不能为空外) /// specificProperties=null并且validateProperties=null对所有属性验证只验证其是否合法不验证是否为空(除属性标识指定了不能为空外)
/// specificProperties!=null对指定属性校验并且都必须有值 /// specificProperties!=null对指定属性校验并且都必须有值
@ -630,10 +694,13 @@ namespace Infrastructure.Extensions
/// <param name="specificProperties">验证指定的属性,并且非空判断</param> /// <param name="specificProperties">验证指定的属性,并且非空判断</param>
/// <param name="validateProperties">验证指定属性,只对字段合法性判断,不验证是否为空</param> /// <param name="validateProperties">验证指定属性,只对字段合法性判断,不验证是否为空</param>
/// <returns></returns> /// <returns></returns>
public static WebResponseContent ValidationEntity<T>(this T entity, string[] specificProperties, string[] validateProperties = null) public static void ValidationEntity<T>(this T entity, string[] specificProperties,
string[] validateProperties = null)
{ {
WebResponseContent responseData = new WebResponseContent(); if (entity == null)
if (entity == null) return responseData.Error("对象不能为null"); {
throw new Exception("对象不能为null");
}
PropertyInfo[] propertyArray = typeof(T).GetProperties(); PropertyInfo[] propertyArray = typeof(T).GetProperties();
//若T为object取不到属性 //若T为object取不到属性
@ -641,6 +708,7 @@ namespace Infrastructure.Extensions
{ {
propertyArray = entity.GetType().GetProperties(); propertyArray = entity.GetType().GetProperties();
} }
List<PropertyInfo> compareProper = new List<PropertyInfo>(); List<PropertyInfo> compareProper = new List<PropertyInfo>();
//只验证数据合法性,验证非空 //只验证数据合法性,验证非空
@ -654,15 +722,17 @@ namespace Infrastructure.Extensions
{ {
compareProper.AddRange(propertyArray.Where(x => validateProperties.Contains(x.Name))); compareProper.AddRange(propertyArray.Where(x => validateProperties.Contains(x.Name)));
} }
if (compareProper.Count() > 0) if (compareProper.Count() > 0)
{ {
propertyArray = compareProper.ToArray(); propertyArray = compareProper.ToArray();
} }
foreach (PropertyInfo propertyInfo in propertyArray) foreach (PropertyInfo propertyInfo in propertyArray)
{ {
object value = propertyInfo.GetValue(entity); object value = propertyInfo.GetValue(entity);
//设置默认状态的值 //设置默认状态的值
if (propertyInfo.Name == "Enable" || propertyInfo.Name == "AuditStatus") if (propertyInfo.Name == "Enable")
{ {
if (value == null) if (value == null)
{ {
@ -670,14 +740,16 @@ namespace Infrastructure.Extensions
continue; continue;
} }
} }
//若存在specificProperties并且属性为数组specificProperties中的值校验时就需要判断是否为空 //若存在specificProperties并且属性为数组specificProperties中的值校验时就需要判断是否为空
var reslut = propertyInfo.ValidationProperty(value, var reslut = propertyInfo.ValidationProperty(value,
specificProperties != null && specificProperties.Contains(propertyInfo.Name) ? true : false specificProperties != null && specificProperties.Contains(propertyInfo.Name) ? true : false
); );
if (!reslut.Item1) if (!reslut.Item1)
return responseData.Error(reslut.Item2); {
throw new Exception(reslut.Item2);
}
} }
return responseData.OK();
} }
/// <summary> /// <summary>
@ -687,12 +759,13 @@ namespace Infrastructure.Extensions
/// <returns></returns> /// <returns></returns>
public static string GetSqlDbType(this PropertyInfo propertyInfo) public static string GetSqlDbType(this PropertyInfo propertyInfo)
{ {
string dbType = propertyInfo.GetTypeCustomValue<ColumnAttribute>(x => new { x.TypeName }); string dbType = propertyInfo.GetTypeCustomValue<ColumnAttribute>(x => new {x.TypeName});
if (string.IsNullOrEmpty(dbType)) if (string.IsNullOrEmpty(dbType))
{ {
return dbType; return dbType;
} }
dbType = dbType.ToLower(); dbType = dbType.ToLower();
if (dbType.Contains(SqlDbTypeName.NVarChar)) if (dbType.Contains(SqlDbTypeName.NVarChar))
{ {
@ -723,7 +796,8 @@ namespace Infrastructure.Extensions
/// </param> /// </param>
/// <param name="value"></param> /// <param name="value"></param>
/// <returns>IEnumerable<(bool, string, object)> bool成否校验成功,string校验失败信息,object,当前校验的值</returns> /// <returns>IEnumerable<(bool, string, object)> bool成否校验成功,string校验失败信息,object,当前校验的值</returns>
public static IEnumerable<(bool, string, object)> ValidationValueForDbType(this PropertyInfo propertyInfo, params object[] values) public static IEnumerable<(bool, string, object)> ValidationValueForDbType(this PropertyInfo propertyInfo,
params object[] values)
{ {
string dbTypeName = propertyInfo.GetTypeCustomValue<ColumnAttribute>(c => c.TypeName); string dbTypeName = propertyInfo.GetTypeCustomValue<ColumnAttribute>(c => c.TypeName);
foreach (object value in values) foreach (object value in values)
@ -732,29 +806,33 @@ namespace Infrastructure.Extensions
} }
} }
public static bool ValidationRquiredValueForDbType(this PropertyInfo propertyInfo, object value, out string message) public static bool ValidationRquiredValueForDbType(this PropertyInfo propertyInfo, object value,
out string message)
{ {
if (value == null || value?.ToString()?.Trim() == "") if (value == null || value?.ToString()?.Trim() == "")
{ {
message = $"{propertyInfo.GetDisplayName()}不能为空"; message = $"{propertyInfo.GetDisplayName()}不能为空";
return false; return false;
} }
var result = propertyInfo.GetProperWithDbType().ValidationVal(value, propertyInfo); var result = propertyInfo.GetProperWithDbType().ValidationVal(value, propertyInfo);
message = result.Item2; message = result.Item2;
return result.Item1; return result.Item1;
} }
private static readonly Dictionary<Type, string> ProperWithDbType = new Dictionary<Type, string>() { private static readonly Dictionary<Type, string> ProperWithDbType = new Dictionary<Type, string>()
{ typeof(string),SqlDbTypeName.NVarChar }, {
{ typeof(DateTime),SqlDbTypeName.DateTime}, {typeof(string), SqlDbTypeName.NVarChar},
{typeof(long),SqlDbTypeName.BigInt }, {typeof(DateTime), SqlDbTypeName.DateTime},
{typeof(int),SqlDbTypeName.Int}, {typeof(long), SqlDbTypeName.BigInt},
{ typeof(decimal),SqlDbTypeName.Decimal }, {typeof(int), SqlDbTypeName.Int},
{ typeof(float),SqlDbTypeName.Float }, {typeof(decimal), SqlDbTypeName.Decimal},
{ typeof(double),SqlDbTypeName.Double }, {typeof(float), SqlDbTypeName.Float},
{ typeof(byte),SqlDbTypeName.Int },//类型待完 {typeof(double), SqlDbTypeName.Double},
{ typeof(Guid),SqlDbTypeName.UniqueIdentifier} {typeof(byte), SqlDbTypeName.Int}, //类型待完
{typeof(Guid), SqlDbTypeName.UniqueIdentifier}
}; };
public static string GetProperWithDbType(this PropertyInfo propertyInfo) public static string GetProperWithDbType(this PropertyInfo propertyInfo)
{ {
bool result = ProperWithDbType.TryGetValue(propertyInfo.PropertyType, out string value); bool result = ProperWithDbType.TryGetValue(propertyInfo.PropertyType, out string value);
@ -762,6 +840,7 @@ namespace Infrastructure.Extensions
{ {
return value; return value;
} }
return SqlDbTypeName.NVarChar; return SqlDbTypeName.NVarChar;
} }
@ -772,12 +851,14 @@ namespace Infrastructure.Extensions
/// <param name="value">值</param> /// <param name="value">值</param>
/// <param name="propertyInfo">要验证的类的属性若不为null则会判断字符串的长度是否正确</param> /// <param name="propertyInfo">要验证的类的属性若不为null则会判断字符串的长度是否正确</param>
/// <returns>(bool, string, object)bool成否校验成功,string校验失败信息,object,当前校验的值</returns> /// <returns>(bool, string, object)bool成否校验成功,string校验失败信息,object,当前校验的值</returns>
public static (bool, string, object) ValidationVal(this string dbType, object value, PropertyInfo propertyInfo = null) public static (bool, string, object) ValidationVal(this string dbType, object value,
PropertyInfo propertyInfo = null)
{ {
if (string.IsNullOrEmpty(dbType)) if (string.IsNullOrEmpty(dbType))
{ {
dbType = propertyInfo != null ? propertyInfo.GetProperWithDbType() : SqlDbTypeName.NVarChar; dbType = propertyInfo != null ? propertyInfo.GetProperWithDbType() : SqlDbTypeName.NVarChar;
} }
dbType = dbType.ToLower(); dbType = dbType.ToLower();
string val = value?.ToString(); string val = value?.ToString();
//验证长度 //验证长度
@ -824,7 +905,6 @@ namespace Infrastructure.Extensions
|| dbType == SqlDbTypeName.Char || dbType == SqlDbTypeName.Char
|| dbType == SqlDbTypeName.Text)) || dbType == SqlDbTypeName.Text))
{ {
//默认nvarchar(max) 、text 长度不能超过20000 //默认nvarchar(max) 、text 长度不能超过20000
if (val.Length > 20000) if (val.Length > 20000)
{ {
@ -832,8 +912,13 @@ namespace Infrastructure.Extensions
} }
else else
{ {
int length = StringExtension.GetInt(propertyInfo.GetTypeCustomValue<MaxLengthAttribute>(x => new { x.Length })); int length =
if (length == 0) { return (true, null, null); } StringExtension.GetInt(
propertyInfo.GetTypeCustomValue<MaxLengthAttribute>(x => new {x.Length}));
if (length == 0)
{
return (true, null, null);
}
//判断双字节与单字段 //判断双字节与单字段
else if (length < 8000 && else if (length < 8000 &&
((dbType.Substring(0, 1) != "n" ((dbType.Substring(0, 1) != "n"
@ -845,20 +930,23 @@ namespace Infrastructure.Extensions
} }
} }
} }
if (!string.IsNullOrEmpty(reslutMsg) && propertyInfo != null) if (!string.IsNullOrEmpty(reslutMsg) && propertyInfo != null)
{ {
reslutMsg = propertyInfo.GetDisplayName() + reslutMsg; reslutMsg = propertyInfo.GetDisplayName() + reslutMsg;
} }
return (reslutMsg == "" ? true : false, reslutMsg, value); return (reslutMsg == "" ? true : false, reslutMsg, value);
} }
public static string GetDisplayName(this PropertyInfo property) public static string GetDisplayName(this PropertyInfo property)
{ {
string displayName = property.GetTypeCustomValue<DisplayAttribute>(x => new { x.Name }); string displayName = property.GetTypeCustomValue<DisplayAttribute>(x => new {x.Name});
if (string.IsNullOrEmpty(displayName)) if (string.IsNullOrEmpty(displayName))
{ {
return property.Name; return property.Name;
} }
return displayName; return displayName;
} }
@ -869,22 +957,28 @@ namespace Infrastructure.Extensions
/// <param name="objectVal">属性的值</param> /// <param name="objectVal">属性的值</param>
/// <param name="required">是否指定当前属性必须有值</param> /// <param name="required">是否指定当前属性必须有值</param>
/// <returns></returns> /// <returns></returns>
public static (bool, string, object) ValidationProperty(this PropertyInfo propertyInfo, object objectVal, bool required) public static (bool, string, object) ValidationProperty(this PropertyInfo propertyInfo, object objectVal,
bool required)
{ {
if (propertyInfo.IsKey()) { return (true, null, objectVal); } if (propertyInfo.IsKey())
{
return (true, null, objectVal);
}
string val = objectVal == null ? "" : objectVal.ToString().Trim(); string val = objectVal == null ? "" : objectVal.ToString().Trim();
string requiredMsg = string.Empty; string requiredMsg = string.Empty;
if (!required) if (required)
{ {
var reuireVal = propertyInfo.GetTypeCustomValues<RequiredAttribute>(x => new { x.AllowEmptyStrings, x.ErrorMessage }); var reuireVal =
propertyInfo.GetTypeCustomValues<RequiredAttribute>(x => new {x.AllowEmptyStrings, x.ErrorMessage});
if (reuireVal != null && !Convert.ToBoolean(reuireVal["AllowEmptyStrings"])) if (reuireVal != null && !Convert.ToBoolean(reuireVal["AllowEmptyStrings"]))
{ {
required = true; required = true;
requiredMsg = reuireVal["ErrorMessage"]; requiredMsg = reuireVal["ErrorMessage"];
} }
} }
//如果不要求为必填项并且值为空,直接返回 //如果不要求为必填项并且值为空,直接返回
if (!required && string.IsNullOrEmpty(val)) if (!required && string.IsNullOrEmpty(val))
return (true, null, objectVal); return (true, null, objectVal);
@ -892,17 +986,25 @@ namespace Infrastructure.Extensions
if ((required && val == string.Empty)) if ((required && val == string.Empty))
{ {
if (requiredMsg != "") return (false, requiredMsg, objectVal); if (requiredMsg != "") return (false, requiredMsg, objectVal);
string propertyName = propertyInfo.GetTypeCustomValue<DisplayAttribute>(x => new { x.Name }); string propertyName = propertyInfo.GetTypeCustomValue<DisplayAttribute>(x => new {x.Name});
return (false, requiredMsg + (string.IsNullOrEmpty(propertyName) ? propertyInfo.Name : propertyName) + "不能为空", objectVal); return (false,
requiredMsg + (string.IsNullOrEmpty(propertyName) ? propertyInfo.Name : propertyName) + "不能为空",
objectVal);
} }
//列名 //列名
string typeName = propertyInfo.GetSqlDbType(); string typeName = propertyInfo.GetSqlDbType();
//如果没有ColumnAttribute的需要单独再验证下面只验证有属性的 //如果没有ColumnAttribute的需要单独再验证下面只验证有属性的
if (typeName == null) { return (true, null, objectVal); } if (typeName == null)
{
return (true, null, objectVal);
}
//验证长度 //验证长度
return typeName.ValidationVal(val, propertyInfo); return typeName.ValidationVal(val, propertyInfo);
} }
/// <summary> /// <summary>
/// 获取属性的指定属性 /// 获取属性的指定属性
/// </summary> /// </summary>
@ -928,6 +1030,7 @@ namespace Infrastructure.Extensions
if (obj.Length == 0) return null; if (obj.Length == 0) return null;
return obj[0]; return obj[0];
} }
/// <summary> /// <summary>
/// 获取类的多个指定属性的值 /// 获取类的多个指定属性的值
/// </summary> /// </summary>
@ -935,7 +1038,8 @@ namespace Infrastructure.Extensions
/// <param name="type">指定的类</param> /// <param name="type">指定的类</param>
/// <param name="expression">指定属性的值 格式 Expression<Func<entityt, object>> exp = x => new { x.字段1, x.字段2 };</param> /// <param name="expression">指定属性的值 格式 Expression<Func<entityt, object>> exp = x => new { x.字段1, x.字段2 };</param>
/// <returns>返回的是字段+value</returns> /// <returns>返回的是字段+value</returns>
public static Dictionary<string, string> GetTypeCustomValues<TEntity>(this MemberInfo member, Expression<Func<TEntity, object>> expression) public static Dictionary<string, string> GetTypeCustomValues<TEntity>(this MemberInfo member,
Expression<Func<TEntity, object>> expression)
{ {
var attr = member.GetTypeCustomAttributes(typeof(TEntity)); var attr = member.GetTypeCustomAttributes(typeof(TEntity));
if (attr == null) if (attr == null)
@ -953,6 +1057,7 @@ namespace Infrastructure.Extensions
propertyKeyValues[property.Name] = (property.GetValue(attr) ?? string.Empty).ToString(); propertyKeyValues[property.Name] = (property.GetValue(attr) ?? string.Empty).ToString();
} }
} }
return propertyKeyValues; return propertyKeyValues;
} }
@ -963,15 +1068,18 @@ namespace Infrastructure.Extensions
/// <param name="type">指定的类</param> /// <param name="type">指定的类</param>
/// <param name="expression">指定属性的值 格式 Expression<Func<entityt, object>> exp = x => new { x.字段1, x.字段2 };</param> /// <param name="expression">指定属性的值 格式 Expression<Func<entityt, object>> exp = x => new { x.字段1, x.字段2 };</param>
/// <returns></returns> /// <returns></returns>
public static string GetTypeCustomValue<TEntity>(this MemberInfo member, Expression<Func<TEntity, object>> expression) public static string GetTypeCustomValue<TEntity>(this MemberInfo member,
Expression<Func<TEntity, object>> expression)
{ {
var propertyKeyValues = member.GetTypeCustomValues(expression); var propertyKeyValues = member.GetTypeCustomValues(expression);
if (propertyKeyValues == null || propertyKeyValues.Count == 0) if (propertyKeyValues == null || propertyKeyValues.Count == 0)
{ {
return null; return null;
} }
return propertyKeyValues.First().Value ?? ""; return propertyKeyValues.First().Value ?? "";
} }
/// <summary> /// <summary>
/// 判断hash的列是否为对应的实体并且值是否有效 /// 判断hash的列是否为对应的实体并且值是否有效
/// </summary> /// </summary>
@ -979,12 +1087,14 @@ namespace Infrastructure.Extensions
/// <param name="dic"></param> /// <param name="dic"></param>
/// <param name="removeNotContains">移除不存在字段</param> /// <param name="removeNotContains">移除不存在字段</param>
/// <returns></returns> /// <returns></returns>
public static string ValidateDicInEntity(this Type typeinfo, Dictionary<string, object> dic, bool removeNotContains, string[] ignoreFields = null) public static string ValidateDicInEntity(this Type typeinfo, Dictionary<string, object> dic,
bool removeNotContains, string[] ignoreFields = null)
{ {
return typeinfo.ValidateDicInEntity(dic, removeNotContains, true, ignoreFields); return typeinfo.ValidateDicInEntity(dic, removeNotContains, true, ignoreFields);
} }
public static string ValidateDicInEntity(this Type type, List<Dictionary<string, object>> dicList, bool removeNotContains, bool removerKey, string[] ignoreFields = null) public static string ValidateDicInEntity(this Type type, List<Dictionary<string, object>> dicList,
bool removeNotContains, bool removerKey, string[] ignoreFields = null)
{ {
PropertyInfo[] propertyInfo = type.GetProperties(); PropertyInfo[] propertyInfo = type.GetProperties();
string reslutMsg = string.Empty; string reslutMsg = string.Empty;
@ -994,12 +1104,16 @@ namespace Infrastructure.Extensions
if (!string.IsNullOrEmpty(reslutMsg)) if (!string.IsNullOrEmpty(reslutMsg))
return reslutMsg; return reslutMsg;
} }
return reslutMsg; return reslutMsg;
} }
public static string ValidateDicInEntity(this Type type, Dictionary<string, object> dic, bool removeNotContains, bool removerKey, string[] ignoreFields = null)
public static string ValidateDicInEntity(this Type type, Dictionary<string, object> dic, bool removeNotContains,
bool removerKey, string[] ignoreFields = null)
{ {
return type.ValidateDicInEntity(dic, null, removeNotContains, removerKey, ignoreFields); return type.ValidateDicInEntity(dic, null, removeNotContains, removerKey, ignoreFields);
} }
/// <summary> /// <summary>
/// 判断hash的列是否为对应的实体并且值是否有效 /// 判断hash的列是否为对应的实体并且值是否有效
/// </summary> /// </summary>
@ -1008,9 +1122,14 @@ namespace Infrastructure.Extensions
/// <param name="removeNotContains">移除不存在字段</param> /// <param name="removeNotContains">移除不存在字段</param>
/// <param name="removerKey">移除主键</param> /// <param name="removerKey">移除主键</param>
/// <returns></returns> /// <returns></returns>
private static string ValidateDicInEntity(this Type typeinfo, Dictionary<string, object> dic, PropertyInfo[] propertyInfo, bool removeNotContains, bool removerKey, string[] ignoreFields = null) private static string ValidateDicInEntity(this Type typeinfo, Dictionary<string, object> dic,
PropertyInfo[] propertyInfo, bool removeNotContains, bool removerKey, string[] ignoreFields = null)
{ {
if (dic == null || dic.Count == 0) { return "参数无效"; } if (dic == null || dic.Count == 0)
{
return "参数无效";
}
if (propertyInfo == null) if (propertyInfo == null)
propertyInfo = typeinfo.GetProperties().Where(x => x.PropertyType.Name != "List`1").ToArray(); propertyInfo = typeinfo.GetProperties().Where(x => x.PropertyType.Name != "List`1").ToArray();
@ -1025,6 +1144,7 @@ namespace Infrastructure.Extensions
{ {
dic.Remove(keyName); dic.Remove(keyName);
} }
foreach (PropertyInfo property in propertyInfo) foreach (PropertyInfo property in propertyInfo)
{ {
//忽略与主键的字段不做验证 //忽略与主键的字段不做验证
@ -1045,8 +1165,10 @@ namespace Infrastructure.Extensions
{ {
return property.GetTypeCustomValue<DisplayAttribute>(x => x.Name) + "为必须提交项"; return property.GetTypeCustomValue<DisplayAttribute>(x => x.Name) + "为必须提交项";
} }
continue; continue;
} }
bool isEdit = property.ContainsCustomAttributes(typeof(EditableAttribute)); bool isEdit = property.ContainsCustomAttributes(typeof(EditableAttribute));
//不是编辑列的直接移除,并且不是主键 //不是编辑列的直接移除,并且不是主键
//removerKey=true不保留主键直接移除 //removerKey=true不保留主键直接移除
@ -1058,9 +1180,11 @@ namespace Infrastructure.Extensions
{ {
return property.GetTypeCustomValue<DisplayAttribute>(x => x.Name) + "没有配置好Model为编辑列"; return property.GetTypeCustomValue<DisplayAttribute>(x => x.Name) + "没有配置好Model为编辑列";
} }
dic.Remove(property.Name); dic.Remove(property.Name);
continue; continue;
} }
////移除忽略的不保存的数据 ////移除忽略的不保存的数据
//if (property.ContainsCustomAttributes(typeof(JsonIgnoreAttribute))) //if (property.ContainsCustomAttributes(typeof(JsonIgnoreAttribute)))
//{ //{
@ -1076,20 +1200,24 @@ namespace Infrastructure.Extensions
if (dic[property.Name] != null && dic[property.Name].ToString() == string.Empty) if (dic[property.Name] != null && dic[property.Name].ToString() == string.Empty)
dic[property.Name] = null; dic[property.Name] = null;
} }
return string.Empty; return string.Empty;
} }
private static object MapToInstance(this Type reslutType, object sourceEntity, PropertyInfo[] sourcePro, PropertyInfo[] reslutPro, string[] sourceFilterField, string[] reslutFilterField, string mapType = null) private static object MapToInstance(this Type reslutType, object sourceEntity, PropertyInfo[] sourcePro,
PropertyInfo[] reslutPro, string[] sourceFilterField, string[] reslutFilterField, string mapType = null)
{ {
mapType = mapType ?? GetMapType(reslutType); mapType = mapType ?? GetMapType(reslutType);
if (sourcePro == null) if (sourcePro == null)
{ {
sourcePro = sourceEntity.GetType().GetProperties(); sourcePro = sourceEntity.GetType().GetProperties();
} }
if (reslutPro == null) if (reslutPro == null)
{ {
reslutPro = reslutType.GetProperties(); ; reslutPro = reslutType.GetProperties();
;
} }
object newObj = Activator.CreateInstance(reslutType); object newObj = Activator.CreateInstance(reslutType);
@ -1100,10 +1228,12 @@ namespace Infrastructure.Extensions
{ {
sourcePro = sourcePro.Where(x => sourceFilterField.Contains(x.Name)).ToArray(); sourcePro = sourcePro.Where(x => sourceFilterField.Contains(x.Name)).ToArray();
} }
foreach (var property in sourcePro) foreach (var property in sourcePro)
{ {
(newObj as System.Collections.IDictionary).Add(property.Name, property.GetValue(sourceEntity)); (newObj as System.Collections.IDictionary).Add(property.Name, property.GetValue(sourceEntity));
} }
return newObj; return newObj;
} }
@ -1119,8 +1249,10 @@ namespace Infrastructure.Extensions
continue; continue;
property.SetValue(newObj, info.GetValue(sourceEntity)); property.SetValue(newObj, info.GetValue(sourceEntity));
} }
return newObj; return newObj;
} }
private static string GetMapType(Type type) private static string GetMapType(Type type)
{ {
return typeof(Dictionary<,>) == type ? "Dictionary" : "entity"; return typeof(Dictionary<,>) == type ? "Dictionary" : "entity";
@ -1136,16 +1268,20 @@ namespace Infrastructure.Extensions
/// <param name="resultExpression">只映射返回对象的指定字段,若为null则默认为全部字段</param> /// <param name="resultExpression">只映射返回对象的指定字段,若为null则默认为全部字段</param>
/// <param name="sourceExpression">只映射数据源对象的指定字段,若为null则默认为全部字段</param> /// <param name="sourceExpression">只映射数据源对象的指定字段,若为null则默认为全部字段</param>
/// <returns></returns> /// <returns></returns>
public static TResult MapToObject<TSource, TResult>(this TSource source, Expression<Func<TResult, object>> resultExpression, public static TResult MapToObject<TSource, TResult>(this TSource source,
Expression<Func<TResult, object>> resultExpression,
Expression<Func<TSource, object>> sourceExpression = null Expression<Func<TSource, object>> sourceExpression = null
) where TResult : class ) where TResult : class
{ {
if (source == null) if (source == null)
return null; return null;
string[] sourceFilterField = sourceExpression == null ? typeof(TSource).GetProperties().Select(x => x.Name).ToArray() : sourceExpression.GetExpressionProperty(); string[] sourceFilterField = sourceExpression == null
? typeof(TSource).GetProperties().Select(x => x.Name).ToArray()
: sourceExpression.GetExpressionProperty();
string[] reslutFilterField = resultExpression?.GetExpressionProperty(); string[] reslutFilterField = resultExpression?.GetExpressionProperty();
if (!(source is System.Collections.IList)) if (!(source is System.Collections.IList))
return MapToInstance(typeof(TResult), source, null, null, sourceFilterField, reslutFilterField) as TResult; return MapToInstance(typeof(TResult), source, null, null, sourceFilterField, reslutFilterField) as
TResult;
Type sourceType = null; Type sourceType = null;
Type resultType = null; Type resultType = null;
@ -1160,9 +1296,11 @@ namespace Infrastructure.Extensions
string mapType = GetMapType(resultType); string mapType = GetMapType(resultType);
for (int i = 0; i < sourceList.Count; i++) for (int i = 0; i < sourceList.Count; i++)
{ {
var reslutobj = MapToInstance(resultType, sourceList[i], sourcePro, resultPro, sourceFilterField, reslutFilterField, mapType); var reslutobj = MapToInstance(resultType, sourceList[i], sourcePro, resultPro, sourceFilterField,
reslutFilterField, mapType);
reslutList.Add(reslutobj); reslutList.Add(reslutobj);
} }
return reslutList as TResult; return reslutList as TResult;
} }
@ -1175,12 +1313,15 @@ namespace Infrastructure.Extensions
/// <param name="source"></param> /// <param name="source"></param>
/// <param name="result"></param> /// <param name="result"></param>
/// <param name="expression">指定对需要的字段赋值,格式x=>new {x.Name,x.P},返回的结果只会对Name与P赋值</param> /// <param name="expression">指定对需要的字段赋值,格式x=>new {x.Name,x.P},返回的结果只会对Name与P赋值</param>
public static void MapValueToEntity<TSource, TResult>(this TSource source, TResult result, Expression<Func<TResult, object>> expression = null) where TResult : class public static void MapValueToEntity<TSource, TResult>(this TSource source, TResult result,
Expression<Func<TResult, object>> expression = null) where TResult : class
{ {
if (source == null) if (source == null)
return; return;
string[] fields = expression?.GetExpressionToArray(); string[] fields = expression?.GetExpressionToArray();
PropertyInfo[] reslutPro = fields == null ? result.GetType().GetProperties() : result.GetType().GetProperties().Where(x => fields.Contains(x.Name)).ToArray(); PropertyInfo[] reslutPro = fields == null
? result.GetType().GetProperties()
: result.GetType().GetProperties().Where(x => fields.Contains(x.Name)).ToArray();
PropertyInfo[] sourcePro = source.GetType().GetProperties(); PropertyInfo[] sourcePro = source.GetType().GetProperties();
foreach (var property in reslutPro) foreach (var property in reslutPro)
{ {
@ -1191,11 +1332,6 @@ namespace Infrastructure.Extensions
} }
} }
} }
} }
public class ArrayEntity public class ArrayEntity

View File

@ -1,7 +1,7 @@
<log4net> <log4net>
<appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender"> <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
<!--定义文件存放位置--> <!--定义文件存放位置-->
<file value="log\\" /> <file value="log/" />
<appendToFile value="true" /> <appendToFile value="true" />
<rollingStyle value="Date" /> <rollingStyle value="Date" />
<datePattern value="yyyyMMdd'.txt'" /> <datePattern value="yyyyMMdd'.txt'" />

View File

@ -65,6 +65,11 @@ namespace OpenAuth.App
/// <returns></returns> /// <returns></returns>
public List<UploadFile> Add(IFormFileCollection files) public List<UploadFile> Add(IFormFileCollection files)
{ {
if (!_auth.CheckLogin())
{
throw new Exception("必需登录才能上传附件");
}
var result = new List<UploadFile>(); var result = new List<UploadFile>();
foreach (var file in files) foreach (var file in files)
{ {

View File

@ -1,4 +1,5 @@
using Infrastructure; using System.ComponentModel.DataAnnotations;
using Infrastructure;
using OpenAuth.Repository.Domain; using OpenAuth.Repository.Domain;
namespace OpenAuth.App.Request namespace OpenAuth.App.Request
@ -18,6 +19,7 @@ namespace OpenAuth.App.Request
/// <summary> /// <summary>
/// </summary> /// </summary>
/// <returns></returns> /// <returns></returns>
[Required(ErrorMessage = "账号肯定不能为空啊~~")]
public string Account { get; set; } public string Account { get; set; }
/// <summary> /// <summary>
@ -27,9 +29,10 @@ namespace OpenAuth.App.Request
/// <summary> /// <summary>
/// 组织名称 /// 用户姓名
/// </summary> /// </summary>
/// <returns></returns> /// <returns></returns>
[Required(ErrorMessage="姓名不能为空")]
public string Name { get; set; } public string Name { get; set; }
@ -50,6 +53,7 @@ namespace OpenAuth.App.Request
/// 所属组织Id多个可用分隔 /// 所属组织Id多个可用分隔
/// </summary> /// </summary>
/// <value>The organizations.</value> /// <value>The organizations.</value>
[Required(ErrorMessage = "请为用户分配机构")]
public string OrganizationIds { get; set; } public string OrganizationIds { get; set; }
public static implicit operator UpdateUserReq(User user) public static implicit operator UpdateUserReq(User user)

View File

@ -1,6 +1,7 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using Microsoft.Extensions.Logging;
using OpenAuth.App.Interface; using OpenAuth.App.Interface;
using OpenAuth.App.Request; using OpenAuth.App.Request;
using OpenAuth.Repository.Domain; using OpenAuth.Repository.Domain;
@ -8,10 +9,13 @@ using OpenAuth.Repository.Interface;
namespace OpenAuth.App namespace OpenAuth.App
{ {
public class RevelanceManagerApp :BaseApp<Relevance> public class RevelanceManagerApp : BaseApp<Relevance>
{ {
public RevelanceManagerApp(IUnitWork unitWork, IRepository<Relevance> repository,IAuth auth) : base(unitWork, repository, auth) private readonly ILogger<RevelanceManagerApp> _logger;
public RevelanceManagerApp(IUnitWork unitWork, IRepository<Relevance> repository, IAuth auth, ILogger<RevelanceManagerApp> logger) : base(unitWork,
repository, auth)
{ {
_logger = logger;
} }
/// <summary> /// <summary>
@ -71,17 +75,24 @@ namespace OpenAuth.App
foreach (var sameVals in idMaps) foreach (var sameVals in idMaps)
{ {
foreach (var value in sameVals) foreach (var value in sameVals)
{
_logger.LogInformation($"start=> delete {key} {sameVals.Key} {value}");
try
{ {
UnitWork.Delete<Relevance>(u => u.Key == key && u.FirstId == sameVals.Key && u.SecondId == value); UnitWork.Delete<Relevance>(u => u.Key == key && u.FirstId == sameVals.Key && u.SecondId == value);
} }
catch (Exception e)
{
_logger.LogError(e,e.Message);
}
_logger.LogInformation($"end=> {key} {sameVals.Key} {value}");
}
} }
UnitWork.Save();
} }
public void DeleteBy(string key, params string[] firstIds) public void DeleteBy(string key, params string[] firstIds)
{ {
UnitWork.Delete<Relevance>(u => firstIds.Contains(u.FirstId) && u.Key == key); UnitWork.Delete<Relevance>(u => firstIds.Contains(u.FirstId) && u.Key == key);
UnitWork.Save();
} }
@ -125,6 +136,11 @@ namespace OpenAuth.App
/// <param name="request"></param> /// <param name="request"></param>
public void AssignData(AssignDataReq request) public void AssignData(AssignDataReq request)
{ {
if (!request.Properties.Any())
{
return;
}
var relevances = new List<Relevance>(); var relevances = new List<Relevance>();
foreach (var requestProperty in request.Properties) foreach (var requestProperty in request.Properties)
{ {
@ -137,6 +153,7 @@ namespace OpenAuth.App
OperateTime = DateTime.Now OperateTime = DateTime.Now
}); });
} }
UnitWork.BatchAdd(relevances.ToArray()); UnitWork.BatchAdd(relevances.ToArray());
UnitWork.Save(); UnitWork.Save();
} }
@ -155,7 +172,7 @@ namespace OpenAuth.App
} }
else //把角色的某一个模块权限全部删除 else //把角色的某一个模块权限全部删除
{ {
DeleteBy(Define.ROLEDATAPROPERTY, new []{ request.ModuleCode }.ToLookup(u =>request.RoleId)); DeleteBy(Define.ROLEDATAPROPERTY, new[] {request.ModuleCode}.ToLookup(u => request.RoleId));
} }
} }
else //按具体的id删除 else //按具体的id删除
@ -167,7 +184,6 @@ namespace OpenAuth.App
&& u.SecondId == request.ModuleCode && u.SecondId == request.ModuleCode
&& u.ThirdId == property); && u.ThirdId == property);
} }
UnitWork.Save();
} }
} }

View File

@ -29,12 +29,17 @@ namespace OpenAuth.App
} }
/// <summary>
/// 添加角色如果当前登录用户不是System则直接把新角色分配给当前登录用户
/// </summary>
public void Add(RoleView obj) public void Add(RoleView obj)
{ {
UnitWork.ExecuteWithTransaction(() =>
{
Role role = obj; Role role = obj;
role.CreateTime = DateTime.Now; role.CreateTime = DateTime.Now;
Repository.Add(role); UnitWork.Add(role);
UnitWork.Save();
obj.Id = role.Id; //要把保存后的ID存入view obj.Id = role.Id; //要把保存后的ID存入view
//如果当前账号不是SYSTEM则直接分配 //如果当前账号不是SYSTEM则直接分配
@ -48,10 +53,13 @@ namespace OpenAuth.App
secIds = new[] {role.Id} secIds = new[] {role.Id}
}); });
} }
});
} }
/// <summary>
/// 更新角色属性
/// </summary>
/// <param name="obj"></param>
public void Update(RoleView obj) public void Update(RoleView obj)
{ {
Role role = obj; Role role = obj;

View File

@ -22,7 +22,7 @@ namespace OpenAuth.App.Test
var cachemock = new Mock<ICacheContext>(); var cachemock = new Mock<ICacheContext>();
cachemock.Setup(x => x.Get<UserAuthSession>("tokentest")) cachemock.Setup(x => x.Get<UserAuthSession>("tokentest"))
.Returns(new UserAuthSession { Account = "System" }); .Returns(new UserAuthSession { Account = Define.SYSTEM_USERNAME });
services.AddScoped(x => cachemock.Object); services.AddScoped(x => cachemock.Object);
var httpContextAccessorMock = new Mock<IHttpContextAccessor>(); var httpContextAccessorMock = new Mock<IHttpContextAccessor>();
@ -56,5 +56,32 @@ namespace OpenAuth.App.Test
Console.WriteLine(JsonHelper.Instance.Serialize(result)); Console.WriteLine(JsonHelper.Instance.Serialize(result));
} }
[Test]
public void UnAssign()
{
var app = _autofacServiceProvider.GetService<RevelanceManagerApp>();
app.UnAssignData(new AssignDataReq
{
ModuleCode = "WmsInboundOrderTbl",
Properties = new string[]{},
RoleId = "09ee2ffa-7463-4938-ae0b-1cb4e80c7c13"
});
app.UnAssignData(new AssignDataReq
{
ModuleCode = "Category",
Properties = new string[]{},
RoleId = "09ee2ffa-7463-4938-ae0b-1cb4e80c7c13"
});
app.UnAssignData(new AssignDataReq
{
ModuleCode = "Resource",
Properties = new string[]{},
RoleId = "09ee2ffa-7463-4938-ae0b-1cb4e80c7c13"
});
}
} }
} }

View File

@ -21,7 +21,7 @@ namespace OpenAuth.App.Test
var cachemock = new Mock<ICacheContext>(); var cachemock = new Mock<ICacheContext>();
cachemock.Setup(x => x.Get<UserAuthSession>("tokentest")) cachemock.Setup(x => x.Get<UserAuthSession>("tokentest"))
.Returns(new UserAuthSession { Account = "System" }); .Returns(new UserAuthSession { Account = Define.SYSTEM_USERNAME });
services.AddScoped(x => cachemock.Object); services.AddScoped(x => cachemock.Object);
var httpContextAccessorMock = new Mock<IHttpContextAccessor>(); var httpContextAccessorMock = new Mock<IHttpContextAccessor>();

View File

@ -20,7 +20,7 @@ namespace OpenAuth.App.Test
var services = new ServiceCollection(); var services = new ServiceCollection();
var cachemock = new Mock<ICacheContext>(); var cachemock = new Mock<ICacheContext>();
cachemock.Setup(x => x.Get<UserAuthSession>("tokentest")).Returns(new UserAuthSession { Account = "System" }); cachemock.Setup(x => x.Get<UserAuthSession>("tokentest")).Returns(new UserAuthSession { Account = Define.SYSTEM_USERNAME });
services.AddScoped(x => cachemock.Object); services.AddScoped(x => cachemock.Object);
var httpContextAccessorMock = new Mock<IHttpContextAccessor>(); var httpContextAccessorMock = new Mock<IHttpContextAccessor>();

View File

@ -17,7 +17,7 @@ namespace OpenAuth.App.Test
var services = new ServiceCollection(); var services = new ServiceCollection();
var cachemock = new Mock<ICacheContext>(); var cachemock = new Mock<ICacheContext>();
cachemock.Setup(x => x.Get<UserAuthSession>("tokentest")).Returns(new UserAuthSession { Account = "System" }); cachemock.Setup(x => x.Get<UserAuthSession>("tokentest")).Returns(new UserAuthSession { Account = Define.SYSTEM_USERNAME});
services.AddScoped(x => cachemock.Object); services.AddScoped(x => cachemock.Object);
var httpContextAccessorMock = new Mock<IHttpContextAccessor>(); var httpContextAccessorMock = new Mock<IHttpContextAccessor>();
@ -28,6 +28,27 @@ namespace OpenAuth.App.Test
return services; return services;
} }
/// <summary>
/// 测试添加用户时,数据校验。
/// 因为请求数据没有AccountName等该测试会提示异常
/// </summary>
[Test]
public void TestValidation()
{
var app = _autofacServiceProvider.GetService<UserManagerApp>();
try
{
app.AddOrUpdate(new UpdateUserReq
{
OrganizationIds = "08f41bf6-4388-4b1e-bd3e-2ff538b44b1b",
});
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
[Test] [Test]
public void TestAdd() public void TestAdd()
{ {

View File

@ -3,6 +3,7 @@ using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Threading.Tasks; using System.Threading.Tasks;
using Castle.Core.Internal; using Castle.Core.Internal;
using Infrastructure.Extensions;
using OpenAuth.App.Interface; using OpenAuth.App.Interface;
using OpenAuth.App.Request; using OpenAuth.App.Request;
using OpenAuth.App.Response; using OpenAuth.App.Response;
@ -115,6 +116,8 @@ namespace OpenAuth.App
public void AddOrUpdate(UpdateUserReq request) public void AddOrUpdate(UpdateUserReq request)
{ {
request.ValidationEntity(u => new {u.Account,u.Name, u.OrganizationIds});
if (string.IsNullOrEmpty(request.OrganizationIds)) if (string.IsNullOrEmpty(request.OrganizationIds))
throw new Exception("请为用户分配机构"); throw new Exception("请为用户分配机构");
User requser = request; User requser = request;

View File

@ -6,6 +6,7 @@ using System.Collections.Generic;
using System.Security.Claims; using System.Security.Claims;
using IdentityModel; using IdentityModel;
using IdentityServer4.Test; using IdentityServer4.Test;
using OpenAuth.App;
namespace OpenAuth.IdentityServer.Quickstart namespace OpenAuth.IdentityServer.Quickstart
{ {
@ -13,7 +14,7 @@ namespace OpenAuth.IdentityServer.Quickstart
{ {
public static List<TestUser> Users = new List<TestUser> public static List<TestUser> Users = new List<TestUser>
{ {
new TestUser{SubjectId = "System", Username = "System", Password = "123456", new TestUser{SubjectId = "System", Username = Define.SYSTEM_USERNAME, Password = Define.SYSTEM_USERPWD,
Claims = Claims =
{ {
new Claim(JwtClaimTypes.Name, "System"), new Claim(JwtClaimTypes.Name, "System"),

View File

@ -1,15 +1,31 @@
using Microsoft.EntityFrameworkCore; using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Console;
using OpenAuth.Repository.Domain; using OpenAuth.Repository.Domain;
using OpenAuth.Repository.QueryObj; using OpenAuth.Repository.QueryObj;
namespace OpenAuth.Repository namespace OpenAuth.Repository
{ {
public partial class OpenAuthDBContext : DbContext public partial class OpenAuthDBContext : DbContext
{ {
public OpenAuthDBContext(DbContextOptions<OpenAuthDBContext> options) private ILoggerFactory _LoggerFactory;
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.EnableSensitiveDataLogging (true); //允许打印参数
optionsBuilder.UseLoggerFactory (_LoggerFactory);
base.OnConfiguring (optionsBuilder);
}
public OpenAuthDBContext(DbContextOptions<OpenAuthDBContext> options, ILoggerFactory loggerFactory)
: base(options) : base(options)
{} {
_LoggerFactory = loggerFactory;
}
protected override void OnModelCreating(ModelBuilder modelBuilder) protected override void OnModelCreating(ModelBuilder modelBuilder)
{ {

View File

@ -91,14 +91,18 @@ namespace OpenAuth.WebApi.Controllers
/// </summary> /// </summary>
/// <param name="request"></param> /// <param name="request"></param>
/// <returns></returns> /// <returns></returns>
private static string lockobj = "lock";
[HttpPost] [HttpPost]
public Response UnAssignDataProperty(AssignDataReq request) public Response UnAssignDataProperty(AssignDataReq request)
{ {
var result = new Response(); var result = new Response();
try try
{
lock (lockobj)
{ {
_app.UnAssignData(request); _app.UnAssignData(request);
} }
}
catch (Exception ex) catch (Exception ex)
{ {
result.Code = 500; result.Code = 500;

View File

@ -67,7 +67,6 @@ namespace OpenAuth.WebApi.Controllers
/// <param name="files"></param> /// <param name="files"></param>
/// <returns>服务器存储的文件信息</returns> /// <returns>服务器存储的文件信息</returns>
[HttpPost] [HttpPost]
[AllowAnonymous]
public Response<IList<UploadFile>> Upload(IFormFileCollection files) public Response<IList<UploadFile>> Upload(IFormFileCollection files)
{ {
var result = new Response<IList<UploadFile>>(); var result = new Response<IList<UploadFile>>();

View File

@ -41,7 +41,9 @@ namespace OpenAuth.WebApi.Controllers
return result; return result;
} }
//添加或修改 /// <summary>
/// 添加角色如果当前登录用户不是System则直接把新角色分配给当前登录用户
/// </summary>
[HttpPost] [HttpPost]
public Response<RoleView> Add(RoleView obj) public Response<RoleView> Add(RoleView obj)
{ {
@ -61,7 +63,11 @@ namespace OpenAuth.WebApi.Controllers
return result; return result;
} }
//添加或修改 /// <summary>
/// 更新角色属性
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
[HttpPost] [HttpPost]
public Response Update(RoleView obj) public Response Update(RoleView obj)
{ {

View File

@ -17,8 +17,6 @@ namespace OpenAuth.WebApi
.ConfigureLogging((hostingContext, logging) => .ConfigureLogging((hostingContext, logging) =>
{ {
logging.ClearProviders(); //去掉默认的日志 logging.ClearProviders(); //去掉默认的日志
logging.AddFilter("System", LogLevel.Error);
logging.AddFilter("Microsoft", LogLevel.Error);
logging.AddLog4Net(); logging.AddLog4Net();
}) })
.UseServiceProviderFactory( .UseServiceProviderFactory(

View File

@ -4,10 +4,10 @@ using System.IO;
using System.Linq; using System.Linq;
using Autofac; using Autofac;
using IdentityServer4.AccessTokenValidation; using IdentityServer4.AccessTokenValidation;
using Infrastructure.Extensions;
using Infrastructure.Extensions.AutofacManager; using Infrastructure.Extensions.AutofacManager;
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.DataProtection; using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
@ -38,6 +38,11 @@ namespace OpenAuth.WebApi
// This method gets called by the runtime. Use this method to add services to the container. // This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services) public void ConfigureServices(IServiceCollection services)
{ {
services.Configure<ApiBehaviorOptions>(options =>
{
options.SuppressModelStateInvalidFilter = true;
});
services.AddSingleton(provider => services.AddSingleton(provider =>
{ {
var service = provider.GetRequiredService<ILogger<StartupLogger>>(); var service = provider.GetRequiredService<ILogger<StartupLogger>>();
@ -161,8 +166,10 @@ namespace OpenAuth.WebApi
} }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostEnvironment env) public void Configure(IApplicationBuilder app, IHostEnvironment env, ILoggerFactory loggerFactory)
{ {
loggerFactory.AddLog4Net();
if (env.IsDevelopment()) if (env.IsDevelopment())
{ {
app.UseDeveloperExceptionPage(); app.UseDeveloperExceptionPage();

View File

@ -2,8 +2,9 @@
"Logging": { "Logging": {
"LogLevel": { "LogLevel": {
"Default": "Debug", "Default": "Debug",
"System": "Information", "System": "Error",
"Microsoft": "Information" "Microsoft": "Error",
"Microsoft.EntityFrameworkCore.Database.Command": "Information"
} }
} }
} }