系统:win10 VS版本:2017 .NET Core 版本: 1.1
appsettings.json
配置中添加节点AppSettings services.AddOptions(); services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));
<PackageReference Include="Microsoft.Extensions.Configuration" Version="2.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="2.0.0" />
main函数配置
using Microsoft.Extensions.Configuration;
var Configuration = new ConfigurationBuilder()
.SetBasePath(System.IO.Directory.GetCurrentDirectory())
.AddJsonFile(path: $"appsettings.json")
.AddJsonFile(path: $"appsettings.Test.json",optional:true) //可选,若有存在的key,则test优先级更高
.Build();
System.Console.WriteLine(Configuration.GetSection("test").Value);
参考:https://docs.microsoft.com/en-us/aspnet/core/publishing/iis
亲测可用
public class SecurityHelper
{
#region 加密解密法一
//默认密钥向量
private static byte[] Keys = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F };
/// <summary>
/// DES加密字符串
/// </summary>
/// <param name="encryptString">待加密的字符串</param>
/// <param name="encryptKey">加密密钥,要求为16位</param>
/// <returns>加密成功返回加密后的字符串,失败返回源串</returns>
public static string EncryptDES(string encryptString, string encryptKey = "Key123Ace#321Key")
{
try
{
byte[] rgbKey = Encoding.UTF8.GetBytes(encryptKey.Substring(0, 16));
byte[] rgbIV = Keys;
byte[] inputByteArray = Encoding.UTF8.GetBytes(encryptString);
var DCSP = Aes.Create();
MemoryStream mStream = new MemoryStream();
CryptoStream cStream = new CryptoStream(mStream, DCSP.CreateEncryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
cStream.Write(inputByteArray, 0, inputByteArray.Length);
cStream.FlushFinalBlock();
return Convert.ToBase64String(mStream.ToArray());
}
catch (Exception ex)
{
return ex.Message + encryptString;
}
}
/// <summary>
/// DES解密字符串
/// </summary>
/// <param name="decryptString">待解密的字符串</param>
/// <param name="decryptKey">解密密钥,要求为16位,和加密密钥相同</param>
/// <returns>解密成功返回解密后的字符串,失败返源串</returns>
public static string DecryptDES(string decryptString, string decryptKey = "Key123Ace#321Key")
{
try
{
byte[] rgbKey = Encoding.UTF8.GetBytes(decryptKey.Substring(0, 16));
byte[] rgbIV = Keys;
byte[] inputByteArray = Convert.FromBase64String(decryptString);
var DCSP = Aes.Create();
MemoryStream mStream = new MemoryStream();
CryptoStream cStream = new CryptoStream(mStream, DCSP.CreateDecryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
Byte[] inputByteArrays = new byte[inputByteArray.Length];
cStream.Write(inputByteArray, 0, inputByteArray.Length);
cStream.FlushFinalBlock();
return Encoding.UTF8.GetString(mStream.ToArray());
}
catch (Exception ex)
{
return ex.Message + decryptString;
}
}
#endregion
}
继承Attribute,实现IActionFilter即可 简单校验登录,获取cookie值并解密后得到用户名,未登录则跳转登录(ApplicationKey为自定义的类存放)
public class UserCheckFilterAttribute : Attribute, IActionFilter
{
public void OnActionExecuted(ActionExecutedContext context)
{
}
public void OnActionExecuting(ActionExecutingContext filterContext)
{
string encryptValue = "";
filterContext.HttpContext.Request.Cookies.TryGetValue(ApplicationKey.User_Cookie_Key, out encryptValue);
if (encryptValue == null)
{
filterContext.Result = new RedirectResult("/Account/Login");
return;
}
var userName = SecurityHelper.DecryptDES(encryptValue, ApplicationKey.User_Cookie_Encryption_Key);
if (string.IsNullOrEmpty(userName))
{
filterContext.Result = new RedirectResult("/Account/Login");
return;
}
}
}
Startup.cs
中的ConfigureServices
方法调用services.AddTransient<IUserService,UserService>();
注册服务
调用:
var errMsg="";var result=ExcuteBatFile(path,ref errMsg);
public static string ExcuteBatFile(string batPath, ref string errMsg)
{
if (errMsg == null) throw new ArgumentNullException("errMsg");
string output;
using (Process process = new Process())
{
FileInfo file = new FileInfo(batPath);
if (file.Directory != null)
{
process.StartInfo.WorkingDirectory = file.Directory.FullName;
}
process.StartInfo.FileName = batPath;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = true;
process.StartInfo.UseShellExecute = false;
process.StartInfo.CreateNoWindow = true;
process.Start();
//process.WaitForExit();
output = process.StandardOutput.ReadToEnd();
errMsg = process.StandardError.ReadToEnd();
}
return output;
}
系统需要安装CORE SDK 若上传到git仓库,拉取后需要再项目目录中执行还原命令
dotnet restore
dotnet publish --framework netcoreapp1.1 --output "C:\Publish" --configuration Release
命令相关文档:https://docs.microsoft.com/zh-cn/dotnet/core/tools/
安装Ubuntu(ubuntu-16.04.2-server-amd64.iso) 教程:http://www.cnblogs.com/wangjieguang/p/hyper-v-ubuntu.html 部署文章参考:http://www.cnblogs.com/wangjieguang/p/aspnetcore-ubuntuserver.html Linux下安装SDK https://www.microsoft.com/net/core#linuxubuntu
超详细的Hyper-V安装Ubuntu: http://www.cnblogs.com/wangjieguang/p/hyper-v-ubuntu.html Ubuntu部署.NET Core:http://www.cnblogs.com/wangjieguang/p/aspnetcore-ubuntuserver.html
--------------------2017-07-24记录--------------------
return Json()
时序列化小写的问题在Startup.cs-》ConfigureServices方法配置一下解决
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddMvc()
.AddJsonOptions(op =>
{
//解决序列化后数据小写问题
op.SerializerSettings.ContractResolver =
new Newtonsoft.Json.Serialization.DefaultContractResolver();
//返回数据中有DateTime类型,自定义格式
op.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm";
});
}
ConfigureServices方法中配置即可,详情见院长文章 https://cloud.tencent.com/developer/article/1395027
services.Configure<WebEncoderOptions>(options =>
{
options.TextEncoderSettings = new TextEncoderSettings(UnicodeRanges.All);
});
添加:Console.OutputEncoding = Encoding.Unicode;
添加:context.Response.ContentType = "text/pain;charset=utf-8";
Configure方法中,还是一样的配方
app.UseMvc(routes =>
{
routes.MapRoute(
name: "index",
template: "index.html",
defaults: new { controller = "Home", action = "Index" }
);
routes.MapRoute(
name: "detail",
template: "detail/{id}.html",
defaults: new { controller = "Home", action = "Detail" }
);
routes.MapRoute(
name: "add",
template: "add.html",
defaults: new { controller = "Home", action = "Add" }
);
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
[HttpPost]
public IActionResult Upload(IFormFile file)
{
string previewPath = "";//加域名什么的
long size = 0;
var upFileName = ContentDispositionHeaderValue
.Parse(file.ContentDisposition)
.FileName
.Trim('"');
var fileName = Guid.NewGuid() + Path.GetExtension(upFileName);
size += file.Length;
if (size > UploadMaxLength)
{
return Json(new
{
code = 0,
msg = "图片太大,不能超过5M"
});
}
previewPath += "/uploads/" + fileName;
var savePath = _hostingEnv.WebRootPath + @"\uploads\" + fileName;
var saveDir = _hostingEnv.WebRootPath + @"\uploads\";
if (!Directory.Exists(saveDir))
{
Directory.CreateDirectory(saveDir);
}
using (FileStream fs = System.IO.File.Create(savePath))
{
file.CopyTo(fs);
fs.Flush();
}
return Json(new
{
code = 0,
msg = "上传成功",
data = new
{
src = previewPath,
title = ""
}
});
}
services.AddMvc().AddJsonOptions(op =>
{
op.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm";
});
如果模型中存在非空值类型的字段A:public int 字段A{get;set;}
然后向接口提交一个 {字段A:""}
或者{字段A:null}
提交后会被 ModelState 拦截验证不通过
目前的解决方法有
services.AddMvc().AddJsonOptions(op =>
{
op.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;
op.SerializerSettings.MissingMemberHandling = Newtonsoft.Json.MissingMemberHandling.Ignore;
});
request.HttpContext.Connection.RemoteIpAddress
// GetAbsoluteUri(request)
public string GetAbsoluteUri(HttpRequest request)
{
return new StringBuilder()
.Append(request.Scheme)
.Append("://")
.Append(request.Host)
.Append(request.PathBase)
.Append(request.Path)
.Append(request.QueryString)
.ToString();
}
public class AdminLogAttribute : Attribute, IActionFilter
{
public void OnActionExecuting(ActionExecutingContext filterContext)
{
}
public void OnActionExecuted(ActionExecutedContext context)
{
//获取提交的参数 context.ActionArguments
}
}
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有