系統:win10
VS版本:2017
.NET Core 版本: 1.1
零.讀取配置文件
-
此版本無需添加其他組件
-
在
appsettings.json
配置中添加節點AppSettings
-
添加配置文件的映射模型
-
在Startup.cs ConfigureServices方法中注冊
services.AddOptions(); services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));
-
Controller中使用
-
控制台使用
添加nuget包
<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);
一、登錄記錄session
二、發布.net core1.1.2網站到windos服務器
參考:https://docs.microsoft.com/en-us/aspnet/core/publishing/iis
0. 我的服務器是windows server 2012 ,.net core網站版本為1.1.2
- 經安裝好iis
- 下載安裝:
.NET Core Windows Server Hosting
Microsoft Visual C++ 2015 Redistributable Update 3
- 發布.net core網站到IIS,並將應用池的.NET CLR版本修改為[無托管代碼]
三、DES加密解密算法
親測可用
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/
linux 部署
安裝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 =>
{
//默認使用帕斯卡命名法(oneTwo) CamelCasePropertyNamesContractResolver
//若使用駱駝命名法可使用DefaultContractResolver
op.SerializerSettings.ContractResolver =
new Newtonsoft.Json.Serialization.DefaultContractResolver();
//返回數據中有DateTime類型,自定義格式
op.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm";
});
}
視圖中輸出中文會編碼
ConfigureServices方法中配置即可,詳情見園長文章 http://www.cnblogs.com/dudu/p/5879913.html
services.Configure<WebEncoderOptions>(options =>
{
options.TextEncoderSettings = new TextEncoderSettings(UnicodeRanges.All);
});
中文亂碼解決
控制台亂碼
添加:Console.OutputEncoding = Encoding.Unicode;
網頁輸出亂碼
添加:context.Response.ContentType = "text/pain;charset=utf-8";
.net core中配置偽靜態
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 = ""
}
});
}
返回JSON自定義DateTime類型格式
services.AddMvc().AddJsonOptions(op =>
{
op.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm";
});
[FromBody]接口模型驗證類型轉換的問題
如果模型中存在非空值類型的字段A:public int 字段A{get;set;}
然后向接口提交一個 {字段A:""}
或者{字段A:null}
提交后會被 ModelState 攔截驗證不通過
目前的解決方法有
- 修改類型為可空類型
- 全局設置下序列化忽略null和空字符串,目前 [FromForm] 格式的數據不知道如何處理
services.AddMvc().AddJsonOptions(op =>
{
op.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;
op.SerializerSettings.MissingMemberHandling = Newtonsoft.Json.MissingMemberHandling.Ignore;
});
.net core 獲取IP地址
request.HttpContext.Connection.RemoteIpAddress
.net core 獲取請求URL
// 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();
}
.net core 過濾器中獲取提交的post數據
- 文檔地址:https://docs.microsoft.com/zh-cn/aspnet/core/mvc/controllers/filters?view=aspnetcore-2.0#action-filters
- 相關issues:https://github.com/aspnet/Mvc/issues/7251
.net core 實現一個日志過濾器
public class AdminLogAttribute : Attribute, IActionFilter
{
public void OnActionExecuting(ActionExecutingContext filterContext)
{
}
public void OnActionExecuted(ActionExecutedContext context)
{
//獲取提交的參數 context.ActionArguments
}
}