1.Properties:项目启动需要的一些配置:包含了端口号,IP地址
2.wwwroot:js/css/js包
3.MVC----模型试图控制
①.Controller:控制器—负责业务逻辑计算
②.表现层:用来展示各种结果,和用户互动
③.模型:串联在C–V之间,保存数据
4.appsettings:配置文件
5.Program控制台—ASP.NET Core5.0本质就是一个控制台
6.Startup:支持网站运行的一些相关配置
base代表父类(Controller)的别名
1.ViewBag
base.ViewBag.User1 = "张三";
2.ViewData
base.ViewData["User2"] = "李四";
3.TempData
base.TempData["User3"] = "王二麻子";
4.HttpContext.Session.SetString
使用Session需要配置
1.需要在视图中添加引用:@using Microsoft.AspNetCore.Http
2.Startup中ConfigureServices方法中增加:services.AddSession();
3.Startup中Configure方法中增加:app.UseSession();
base.HttpContext.Session.SetString("User4", "赵四儿");
配置展示:
Index.cshtml中:
Startup.cs中:
5.return View();
因为方法重载的原因,View()传入的值只能为object类型,传入string类型会自动被认为是传入的View名
object User5 = "刘六儿";
return View(User5);
页面上取值:
@using Microsoft.AspNetCore.Http
@{
<h3>User1=@base.ViewBag.User1 </h3>
<h3>User2=@base.ViewData["User2"]</h3>
<h3>User3=@base.TempData["User3"]</h3>
<h3>User4=@base.Context.Session.GetString("User4")</h3>
<h3>User5=@Model</h3>
}
运行出来的效果:
补充:
①.ViewBag 和 ViewData 内部实现是一样的,都是字典支持,如果key一样,后者的值会覆盖前者的值, 比如 :
base.ViewBag.User1 = "张三";
base.ViewData["User1"] = "张三~~张三";
在键同为User1的情况下,最后的运行结果为张三~~张三
②.跨页面传值可使用的传值方法有
TempData
本质是将值保存到了服务器内存中,但赋值后取值只能取一次,在一个控制器里赋值后,只能有一个视图中取值,在取了一次之后,后面再次取值则取不到
HttpContext.Session.SetString
本质是将值保存到了服务器内存中,赋值后,可随意取用
关于NLog与Log4Net使用的帮助文档
>>>>>>>>>>>>>>>>>>>>>>>>>>>>NLog日志----文件记录: <<<<<<<<<<<<<<<<<<<<<<<<<<<
第一步:安装NuGet程序包
在解决方案上右击,选择管理解决方案的NuGet程序包
切换至浏览,在查找框中输入Nlog.Web.AspNetCore,选择包,选中所有项目,点击安装
搜索框中输入Nlog.Config,选中后选择所有项目,点击安装
安装成功后项目中会增加一个NLog.config
NLog.config文件默认是锁定不可修改状态,所以需要复制一份出去改完之后再覆盖回来
<targets>
<!--
add your targets here
See https://github.com/nlog/NLog/wiki/Targets for possible targets.
See https://github.com/nlog/NLog/wiki/Layout-Renderers for the possible layout renderers.
-->
<!--type:记录的文件类型 name:名称 fileName:全路径/名称 layout:记录文本-->
<target xsi:type="File" name="allfile" fileName = "Log\nlog-all-${shortdate}.log" layout="${longdata}|${logger}|${uppercase:${level}}|${message} ${exception}" />
<target xsi:type="File" name="ownFile-web" fileName = "Log\nlog-my-${shortdate}.log" layout="${longdata}|${logger}|${uppercase:${level}}|${message} ${exception}" />
<!--
Write events to a file with the date in the filename.
<target xsi:type="File" name="f" fileName="${basedir}/logs/${shortdate}.log"
layout="${longdate} ${uppercase:${level}} ${message}" />
-->
</targets>
<!--用来选择记到哪里去-->
<rules>
<!-- add your logging rules here -->
<!--minlevel:日志最小级别 writeTo:要写入的日志name(上面targets定义的)-->
<!--如果日志最小级别是Trace那么就写到targets中name为allfile的日志中-->
<logger name="*" minlevel="Trace" writeTo="allfile"/>
<!--如果设置了final,那么当此路由被匹配到时,不会再执行此路由下方的路由,如果没有匹配到才会继续往下面匹配-->
<logger name="Microsoft.*" minlevel="Trace" final="true"/>
<!--上方路由过滤了所有Microsoft.*的日志,所以此处只会打印Microsoft.*以外的日志-->
<logger name="*" minlevel="Trace" writeTo="ownFile-web"/>
<!--
Write all events with minimal level of Debug (So Debug, Info, Warn, Error and Fatal, but not Trace) to "f"
<logger name="*" minlevel="Debug" writeTo="f" />
-->
</rules>
第三步:实现(Program.cs)
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using NLog.Web;
namespace NET5WebApplication
{
public class Program
{
public static void Main(string[] args)
{
//引用 using NLog.Web; 命名空间
//传入NLog.config的路径,比如如果放在文件夹里 那么就是 NLogBuilder.ConfigureNLog("文件夹名/NLog.config");
NLogBuilder.ConfigureNLog("NLog.config");
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
})
//关于NLog的配置
.ConfigureLogging(logging => {
logging.ClearProviders();//删除其他所有关于日志的配置
logging.SetMinimumLevel(LogLevel.Trace);//设置最小的日志等级为Trace,对应NLog.config中标签里的设定
}).UseNLog()
;
}
}
第四步:调用
在控制器中使用构造函数测试NLog
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
namespace NET5WebApplication.Controllers
{
public class FirstController : Controller
{
private readonly ILogger<FirstController> _ILogger = null;
private readonly ILoggerFactory _ILoggerFactory = null;
//使用构造函数测试NLog
public FirstController(ILogger<FirstController> iLogger, ILoggerFactory iLoggerFactory)
{
_ILogger = iLogger;
_ILogger.LogInformation("_ILogger:" + this.GetType().FullName + "被构造了");
_ILoggerFactory = iLoggerFactory;
ILogger<FirstController> _ILogger2 = _ILoggerFactory.CreateLogger<FirstController>();
_ILogger2.LogInformation($"_ILogger2: {this.GetType().FullName} 被构造了");
}
public IActionResult Index()
{
base.ViewBag.User1 = "张三";
return View();
}
}
}
生成的路径与名字和我们在NLog.config中targets标签里定义的一致
文件内容与NLog.config中rules标签里定义的一致,nlog-my-2022-01-18.log经过了一层路由过滤后,所有nlog-all-2022-01-18.log中存在的Microsoft.开头的日志信息均被过滤
>>>>>>>>>>>>>>>>>>>>>>>>>>>>NLog日志----数据库记录(SqlServer为例): <<<<<<<<<<<<<<<<<<<<<<<<<<<
第一步:安装NuGet程序包
在解决方案上右击,选择管理解决方案的NuGet程序包
切换至浏览,在查找框中输入Microsoft.Data.SqlClient,选择包(切记一定要安装3.0.0版本的),选中所有项目,点击安装
第二步:更改NLog.config文件
targets标签中增加代码
<!--连接SQLServer数据库-->
<!--commandText:给NLogManager表添加后面的字段-->
<target name="AllDatabase" xsi:type="Database"
dbProvider="Microsoft.Data.SqlClient.SqlConnection, Microsoft.Data.SqlClient"
connectionString="Data Source=数据库IP地址;Initial Catalog=数据库名;Persist Security Info=True;User ID=用户名;Password=密码;"
commandText="insert into dbo.NLogManager (Application, Logged, Level, Message,Logger, CallSite, Exception) values (@Application, @Logged, @Level, @Message,@Logger, @Callsite, @Exception);">
<parameter name="@application" layout="AspNetCoreNlog" />
<parameter name="@logged" layout="${date}" />
<parameter name="@level" layout="${level}" />
<parameter name="@message" layout="${message}" />
<parameter name="@logger" layout="${logger}" />
<parameter name="@callSite" layout="${callsite:filename=true}" />
<parameter name="@exception" layout="${exception:tostring}" />
</target>
rules标签中增加代码
<logger name="*" minlevel="Trace" writeTo="AllDatabase" />
数据库创建上方使用的表的脚本
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TABLE [dbo].[NLogManager] (
[Id] [int] IDENTITY(1,1) NOT NULL,
[Application] [nvarchar](50) NOT NULL,
[Logged] [datetime] NOT NULL,
[Level] [nvarchar](50) NOT NULL,
[Message] [nvarchar](max) NOT NULL,
[Logger] [nvarchar](250) NULL,
[Callsite] [nvarchar](max) NULL,
[Exception] [nvarchar](max) NULL,
CONSTRAINT [PK_dbo.Log] PRIMARY KEY CLUSTERED ([Id] ASC)
WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
第三步:实现(Program.cs)
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using NLog.Web;
namespace NET5WebApplication
{
public class Program
{
public static void Main(string[] args)
{
//引用 using NLog.Web; 命名空间
//传入NLog.config的路径,比如如果放在文件夹里 那么就是 NLogBuilder.ConfigureNLog("文件夹名/NLog.config");
NLogBuilder.ConfigureNLog("NLog.config");
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
})
//关于NLog的配置
.ConfigureLogging(logging => {
logging.ClearProviders();//删除其他所有关于日志的配置
logging.SetMinimumLevel(LogLevel.Trace);//设置最小的日志等级为Trace,对应NLog.config中标签里的设定
}).UseNLog()
;
}
}
第四步:调用
在控制器中使用构造函数测试NLog
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
namespace NET5WebApplication.Controllers
{
public class FirstController : Controller
{
private readonly ILogger<FirstController> _ILogger = null;
private readonly ILoggerFactory _ILoggerFactory = null;
//使用构造函数测试NLog
public FirstController(ILogger<FirstController> iLogger, ILoggerFactory iLoggerFactory)
{
_ILogger = iLogger;
_ILogger.LogInformation("_ILogger:" + this.GetType().FullName + "被构造了");
_ILoggerFactory = iLoggerFactory;
ILogger<FirstController> _ILogger2 = _ILoggerFactory.CreateLogger<FirstController>();
_ILogger2.LogInformation($"_ILogger2: {this.GetType().FullName} 被构造了");
}
public IActionResult Index()
{
base.ViewBag.User1 = "张三";
return View();
}
}
}
PS:也可以使用System.Data.SqlClient包进行数据库写入,与上面相比需要更改的地方有:1.引用System.Data.SqlClient包。2.NLog.config中需要替换dbProvider属性为
dbProvider = “System.Data.SqlClient”,其他地方一致
>>>>>>>>>>>>>>>>>>>>>>>>>>>>Log4Net记录日志<<<<<<<<<<<<<<<<<<<<<<<<<<<
第一步:安装NuGet程序包
log4net
Microsoft.Extensions.Logging.Log4Net.AspNetCore
第二步:修改配置文件
项目上右击→添加→新建项→Web配置文件→更改名称为log4net.Config
贴入代码:
<?xml version="1.0" encoding="utf-8"?>
<log4net>
<!-- Define some output appenders -->
<appender name="rollingAppender" type="log4net.Appender.RollingFileAppender">
<file value="log4\log.txt" />
<!--追加日志内容-->
<appendToFile value="true" />
<!--防止多线程时不能写Log,官方说线程非安全-->
<lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
<!--可以为:Once|Size|Date|Composite-->
<!--Composite为Size和Date的组合-->
<rollingStyle value="Composite" />
<!--当备份文件时,为文件名加的后缀-->
<datePattern value="yyyyMMdd.TXT" />
<!--日志最大个数,都是最新的-->
<!--rollingStyle节点为Size时,只能有value个日志-->
<!--rollingStyle节点为Composite时,每天有value个日志-->
<maxSizeRollBackups value="20" />
<!--可用的单位:KB|MB|GB-->
<maximumFileSize value="3MB" />
<!--置为true,当前最新日志文件名永远为file节中的名字-->
<staticLogFileName value="true" />
<!--输出级别在INFO和ERROR之间的日志-->
<filter type="log4net.Filter.LevelRangeFilter">
<param name="LevelMin" value="ALL" />
<param name="LevelMax" value="FATAL" />
</filter>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger - %message%newline"/>
</layout>
</appender>
<root>
<priority value="ALL"/>
<level value="ALL"/>
<appender-ref ref="rollingAppender" />
</root>
</log4net>
将配置文件属性改为始终复制
//关于Log4Net的配置
.ConfigureLogging(logging => {
logging.ClearProviders();//删除其他所有关于日志的配置
logging.SetMinimumLevel(LogLevel.Trace);//设置最小的日志等级为Trace,对应NLog.config中标签里的设定
logging.AddLog4Net("log4net.Config");//如果放在文件夹里 那么就是logging.addLog4Net("文件夹名/log4net.Config");
})
第四步:调用
在控制器中使用构造函数测试NLog
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
namespace NET5WebApplication.Controllers
{
public class FirstController : Controller
{
private readonly ILogger<FirstController> _ILogger = null;
private readonly ILoggerFactory _ILoggerFactory = null;
//使用构造函数测试日志
public FirstController(ILogger<FirstController> iLogger, ILoggerFactory iLoggerFactory)
{
_ILogger = iLogger;
_ILogger.LogInformation("_ILogger:" + this.GetType().FullName + "被构造了");
_ILoggerFactory = iLoggerFactory;
ILogger<FirstController> _ILogger2 = _ILoggerFactory.CreateLogger<FirstController>();
_ILogger2.LogInformation($"_ILogger2: {this.GetType().FullName} 被构造了");
}
public IActionResult Index()
{
base.ViewBag.User1 = "张三";
return View();
}
}
}