系统:win10

VS版本:2017

.NET Core 版本: 1.1

零.读取配置文件

参考:http://www.tuicool.com/articles/QfYVBvi

  1. 此版本无需添加其他组件

  2. appsettings.json配置中添加节点AppSettings

  3. 添加配置文件的映射模型

  4. 在Startup.cs ConfigureServices方法中注册

         services.AddOptions();
    services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));
  5. Controller中使用

  6. 控制台使用

    添加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

参考:http://www.cnblogs.com/fonour/p/5943401.html

二、发布.net core1.1.2网站到windos服务器

参考:https://docs.microsoft.com/en-us/aspnet/core/publishing/iis

0. 我的服务器是windows server 2012 ,.net core网站版本为1.1.2

  1. 经安装好iis
  2. 下载安装:

    .NET Core Windows Server Hosting

    Microsoft Visual C++ 2015 Redistributable Update 3

  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";

参考评论:http://www.cnblogs.com/wolf-sun/p/6136482.html

.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数据

  1. 文档地址:https://docs.microsoft.com/zh-cn/aspnet/core/mvc/controllers/filters?view=aspnetcore-2.0#action-filters
  2. 相关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 } }

.net core建站踩坑记录的更多相关文章

  1. .NET CORE 2.0 踩坑记录之ConfigurationManager

    在之前.net framework 中使用的ConfigurationManager还是很方便的,不过在.NET CORE 2.0中SDK默认已经不存在ConfigurationManager. 那么 ...

  2. manjaro xfce 18.0 踩坑记录

    manjaro xfce 18.0 踩坑记录 1 简介1.1 Manjaro Linux1.2 开发桌面环境2 自动打开 NumLock3 系统快照3.1 安装timeshift3.2 使用times ...

  3. .Net Core建站(3):搭建三层架构

    啊,终于到写三层架构的时候了,老实说,我都不知道自己这个算不算三层架构,姑且就当它是吧,具体属于哪一个体系,希望有大佬指点一下(^o^)/ 不晓得有人注意到没有,我写了三篇博客,然后就改了三次标题ヽ( ...

  4. 你真的了解字典(Dictionary)吗? C# Memory Cache 踩坑记录 .net 泛型 结构化CSS设计思维 WinForm POST上传与后台接收 高效实用的.NET开源项目 .net 笔试面试总结(3) .net 笔试面试总结(2) 依赖注入 C# RSA 加密 C#与Java AES 加密解密

    你真的了解字典(Dictionary)吗?   从一道亲身经历的面试题说起 半年前,我参加我现在所在公司的面试,面试官给了一道题,说有一个Y形的链表,知道起始节点,找出交叉节点.为了便于描述,我把上面 ...

  5. ABP框架踩坑记录

    ABP框架踩坑记录 ASP.NET Boilerplate是一个专用于现代Web应用程序的通用应用程序框架. 它使用了你已经熟悉的工具,并根据它们实现最佳实践. 文章目录 使用MySQL 配置User ...

  6. python发布包到pypi的踩坑记录

    前言 突然想玩玩python了^_^ 这篇博文记录了我打算发布包到pypi的踩坑经历.python更新太快了,甚至连这种发布上传机制都在不断的更新,这导致网上的一些关于python发布上传到pypi的 ...

  7. DevOps落地实践点滴和踩坑记录-(2) -聊聊平台建设

    很久没有写文章记录了,上一篇文章像流水账一样,把所见所闻一个个记录下来.这次专门聊聊DevOps平台的建设吧,有些新的体会和思考,希望给正在做这个事情的同学们一些启发吧. DevOps落地实践点滴和踩 ...

  8. unionId突然不能获取的踩坑记录

    昨天(2016-2-2日),突然发现系统的一个微信接口使用不了了.后来经查发现,是在网页授权获取用户基本信息的时候,unionid获取失败导致的. 在网页授权获取用户基本信息的介绍中(http://m ...

  9. CentOS7.4安装MySQL踩坑记录

    CentOS7.4安装MySQL踩坑记录 time: 2018.3.19 CentOS7.4安装MySQL时网上的文档虽然多但是不靠谱的也多, 可能因为版本与时间的问题, 所以记录下自己踩坑的过程, ...

随机推荐

  1. 数组去重,call、apply、bind之间的区别,this用法总结

    一.数组去重,直接写到Array原型链上. //该方法只能去除相同的数字 不会去判断24和'24'是不同的 所有数字和字符串数字是相同是重复的 Array.prototype.redup=functi ...

  2. 五、 创建连接串连接本地数据库(ASP.NET MVC5 系列)

    1. 创建连接串连接本地SQLServer数据库 上节讲到MovieDBContext类,这个类的作用是连接数据库并将Movie对象迁移到数据库记录中.不过你会问一个问题:如何知道这个对象将连接哪个数 ...

  3. (数字IC)低功耗设计入门(三)——系统与架构级

    前面讲解了使用EDA工具(主要是power compiler)进行功耗分析的流程,这里我们将介绍在数字IC中进行低功耗设计的方法,同时也结合EDA工具(主要是Design Compiler)如何实现. ...

  4. Junit4测试Spring

    使用Junit4.4测试 在类上的配置Annotation  @RunWith(SpringJUnit4ClassRunner.class) 用于配置spring中测试的环境  @ContextCon ...

  5. Asp.Net Core MVC项目实现多语言(Globalization/Localization)

    正好最近手上在给一个Razor MVC项目实现一个多语言功能,叫Globalization也好,Localization也好,whatever.最终要实现的效果呢,就是一键切换全站语言,并且开发的时候 ...

  6. 2017CUIT校赛-线上赛

    2017Pwnhub杯-CUIT校赛 这是CUIT第十三届校赛啦,也是我参加的第一次校赛. 在被虐到崩溃的过程中也学到了一些东西. 这次比赛是从5.27早上十点打到5.28晚上十点,共36小时,中间睡 ...

  7. hdu3715

    hdu3715 题意 给出一个递归的伪代码,当 x[a[dep]] + x[b[dep]] != c[dep],就向下递归,给出a,b,c数组的值 问 dep 最大多少.其中 0 <= c[i] ...

  8. OpenCV中的结构体、类与Emgu.CV的对应表

    OpenCv中的 C 结构 OpenCV中的 C++ 封装 Emgu.CV中的 C# 封装 OpenCV 和 Emgu.CV 中的结构罗列 谢谢阅读,有误希望指正 原文地址 Basic Structu ...

  9. java中static关键字的作用

    java中static关键字主要有两种作用: 第一:为某特定数据类型或对象分配单一的存储空间,而与创建对象的个数无关. 第二,实现某个方法或属性与类而不是对象关联在一起 简单来说,在Java语言中,s ...

  10. vs2015添加ActiveX Control Test Container工具(转载)

    http://blog.csdn.net/lphbtm/article/details/8647565 vs2010 中添加 ActiveX Control Test Container工具(转载) ...