当前位置:网站首页>Asp. Net core1.1 without project JSON, so as to generate cross platform packages
Asp. Net core1.1 without project JSON, so as to generate cross platform packages
2022-07-03 13:23:00 【Brother Xing plays with the clouds】
What this chapter will share with you is Asp.NetCore1.1 Version removed project.json How to package and generate cross platform packages after , For better follow-up AspNetCore The development of , Use it to do netcore Developed vs2015 After uninstalling and installing vs2017, The direct benefit this brings to me is to make me red C Disk free 10GB Left and right space , From here, you can directly feel vs2017 So small ; I wrote an article about open source before netcore Open source a cross platform service plug-in - TaskCore.MainForm, It tells about netcore The project is generated and deployed in win7 and Ubuntu16.04 Examples on the system , Interested friends can go and have a look ; Let's start with this article , I hope you like it
AspNetCore Use in Session( be based on MemoryCache Components )
This section seems a little inconsistent with the article title , The main reason is that there is too little content to write and generate cross platform packages , Some friends feel dissatisfied with too little work , So use this if you use Session Fill it up, haha ( My idea is : Progress day by day , Even a little ); For one web Procedure session There are usually many ways to store , For example, my previous article used Redis To store session Related articles of , That's for a netcore For the project, the default session The storage method is memorycache The way , This can be done in the project Startup.cs In file ConfigureServices Method add the following code snippet :
1 services.AddDistributedMemoryCache(); 2 services.AddSession(b => 3 { 4 b.IdleTimeout = TimeSpan.FromMinutes(1);5 b.CookieName = "MySid"; 6 });
And in Configure Method to add app.UseSession(); session Use ; When copying the above code snippet into your program , Will prompt a small light bulb , You need to click to select the corresponding package , about vs2017 Automatically installed netcore Development environment of , So just click on the light bulb reference , If you haven't installed development sdk, So download nuget package : Microsoft.AspNetCore.Session ; The first paragraph services.AddDistributedMemoryCache() The main function is to add memorycache Store references , The second paragraph AddSession Method is the real addition session Relevant stuff , Here I use two attributes :
1. IdleTimeout: Set up session Expiration time ;
2. CookieName: Set up sessionId Stored in the client browser key name ;
After completing the above steps , It can be done anywhere Controller( Here is HomeController) Of Action Use in HttpContext.Session.Set Method add session:
public IActionResult About() { _logger.LogInformation(" Here is About");
var userInfo = " my NetCore And Session"; HttpContext.Session.Set(SessionKey, System.Text.Encoding.UTF8.GetBytes(userInfo)); ViewData["Message"] = $" Read configuration file Option1 Node values :{this._options.Option1}, add to session"; return View(); }
Then through another Contact Of Action Use in HttpContext.Session.TryGetValue(SessionKey, out var bt) To get what we just set session:
public IActionResult Contact() { var userInfo = string.Empty; if (HttpContext.Session.TryGetValue(SessionKey, out var bt)) { userInfo = System.Text.Encoding.UTF8.GetString(bt); }
ViewData["Message"] = string.IsNullOrWhiteSpace(userInfo) ? "Session Get is empty " : userInfo; return View(); }
Well, that's it , Let's run and see the effect :dontnet run Command to run the test site , Not surprisingly, you will get the following screenshot on the interface :
You can see our... Through the browser console sessionId Its name is MySid, This is just as we are Startup.cs Set up CookieName The same ;
ISession Extension method
Used above Set Methods to save sesseion, Let's take a look at her parameters void Set(string key, byte[] value); The way of key value pair , But the value is a byte[] Parameters of type , Every time we use it, we need to change the data type by ourselves, which is not very convenient , Then let's extend the method ISession , The following extension code :
public static class PublicExtensions { #region ISession Expand
/// <summary> /// Set up session /// </summary> /// <typeparam name="T"></typeparam> /// <param name="session"></param> /// <param name="key"></param> /// <param name="val"></param> /// <returns></returns> public static bool Set<T>(this ISession session, string key, T val) { if (string.IsNullOrWhiteSpace(key) || val == null) { return false; }
var strVal = JsonConvert.SerializeObject(val); var bb = Encoding.UTF8.GetBytes(strVal); session.Set(key, bb); return true; }
/// <summary> /// obtain session /// </summary> /// <typeparam name="T"></typeparam> /// <param name="session"></param> /// <param name="key"></param> /// <returns></returns> public static T Get<T>(this ISession session, string key) { var t = default(T); if (string.IsNullOrWhiteSpace(key)) { return t; }
if (session.TryGetValue(key, out byte[] val)) { var strVal = Encoding.UTF8.GetString(val); t = JsonConvert.DeserializeObject<T>(strVal); } return t; }
#endregion }
Pass an object directly T Into the extension method , Stored after type conversion session In the middle , In order to better test, we directly modify the code on the above test cases, such as :
public IActionResult About() { _logger.LogInformation(" Here is About");
//var userInfo = " my NetCore And Session"; //HttpContext.Session.Set(SessionKey, System.Text.Encoding.UTF8.GetBytes(userInfo));
MoUser user = new MoUser(); HttpContext.Session.Set<MoUser>(SessionKey, user); ViewData["Message"] = $" Read configuration file Option1 Node values :{this._options.Option1}, add to session"; return View(); }
public IActionResult Contact() { //var userInfo = string.Empty; //if (HttpContext.Session.TryGetValue(SessionKey, out var bt)) //{ // userInfo = System.Text.Encoding.UTF8.GetString(bt); //}
//ViewData["Message"] = string.IsNullOrWhiteSpace(userInfo) ? "Session Get is empty " : userInfo;
var user = HttpContext.Session.Get<MoUser>(SessionKey); ViewData["Message"] = user == null ? "Session Get is empty " : $" nickname :{user.UserName}"; return View(); }
look set or get Of session Is it much more convenient to complete the operation with only one sentence of code , Most command :dotnet run Test the effect , Like the above one, I won't take screenshots ;
1.1 Version removed project.json after , How to generate cross platform packages
That brings us to today's topic , For the latest version netcore Get rid of project.json The online discussion is quite intense , However, there is no official Chinese article about how to generate Kua platform package after online search , I'm lucky to be the first one here, hehe ; First , Be clear netcore Group remove project.json After important documents , Its tasks are placed on the project .csproj In file , Yes, it's us vs Generated project engineering files , Let's take the above test case as an example .csproj The content of the document :
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup> <TargetFramework>netcoreapp1.1</TargetFramework> </PropertyGroup> <PropertyGroup> <PackageTargetFallback>$(PackageTargetFallback);portable-net45+win8+wp8+wpa81;</PackageTargetFallback> </PropertyGroup> <ItemGroup> <PackageReference Include="Microsoft.ApplicationInsights.AspNetCore" Version="2.0.0" /> <PackageReference Include="Microsoft.AspNetCore" Version="1.1.1" /> <PackageReference Include="Microsoft.AspNetCore.Mvc" Version="1.1.2" /> <PackageReference Include="Microsoft.AspNetCore.Session" Version="1.1.1" /> <PackageReference Include="Microsoft.AspNetCore.StaticFiles" Version="1.1.1" /> <PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="1.1.1" /> <PackageReference Include="Microsoft.VisualStudio.Web.BrowserLink" Version="1.1.0" /> </ItemGroup> <ItemGroup> <DotNetCliToolReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Tools" Version="1.0.0" /> </ItemGroup> </Project>
Here can be intuitively in ItemGroup The node sees what we added Session And the project template itself Logging Etc , The parent node Project Sdk="Microsoft.NET.Sdk.Web" , We need to generate cross platform running packages , You need to operate the configuration information of the project file , Here you only need to add the following code :
1 <PropertyGroup>
2 <RuntimeIdentifiers>win7-x64;ubuntu.16.04-x64</RuntimeIdentifiers>
3 </PropertyGroup>Then you can generate the platform package by issuing commands , Isn't it quite simple , So I got one on it Session The bar is dry, hehe ; Let's test it , First, execute the command in the project root directory like this :dontnet restore
Then execute your brief command ( Here I directly use the default parameters to execute , The release package will generate bin below ):dotnet publish
At this time, we can be in the directory :bin\Debug\netcoreapp1.1 Here we see publish Folder , Inside is our program execution file , To test the effect , Here I pass the order :dontnet WebApp01.dll ( Because I installed sdk So you can directly run with this command ) To run my test case project :
Here's one windows The package running on is finished , Some friends began to wonder about the cross platform , And what you configured before <RuntimeIdentifiers>win7-x64;ubuntu.16.04-x64</RuntimeIdentifiers> What's the effect , So here's how to generate ubunt.16.04-x64 The running package (win7-x64 In the same way ); We also need to go through :dontnet restore Later, when issuing the order, it was written like this :
dotnet publish -f netcoreapp1.1 --runtime ubuntu.16.04-x64
Command specification :
-f:framework Abbreviation ;
netcoreapp1.1: It's a folder for storage ;
--runtime: It is necessary to run the command ;
ubuntu.16.04-x64: Stored folder name
The final result is in the directory :Debug\netcoreapp1.1 Here's a ubuntu.16.04-x64 Folder , Inside is our running package ; If you want to generate the operation package of other systems, it is the same operation process :
1. In the project .csproj Add the corresponding Runtime command ( Such as :win7-x64;osx.10-11-x64;ubuntu.16.04-x64);
2. stay dotnet publish Change the last parameter to the corresponding Runtime Just order ( Such as :ubuntu.16.04-x64)
This concludes the article , Hope to bring you good help , Thank you for reading ;
边栏推荐
- SQL learning notes (I)
- MyCms 自媒体商城 v3.4.1 发布,使用手册更新
- Swiftui development experience: the five most powerful principles that a programmer needs to master
- Servlet
- CVPR 2022 image restoration paper
- In the promotion season, how to reduce the preparation time of defense materials by 50% and adjust the mentality (personal experience summary)
- sitesCMS v3.1.0发布,上线微信小程序
- 2022-01-27 redis cluster brain crack problem analysis
- Logseq 评测:优点、缺点、评价、学习教程
- Kivy tutorial how to load kV file design interface by string (tutorial includes source code)
猜你喜欢
[email protected]奇安信:透视俄乌网络战 —— 网络空间基础设施面临的安全对抗与制裁博弈..."/>开始报名丨CCF C³[email protected]奇安信:透视俄乌网络战 —— 网络空间基础设施面临的安全对抗与制裁博弈...

Typeerror resolved: argument 'parser' has incorrect type (expected lxml.etree.\u baseparser, got type)

Detailed explanation of multithreading

Sitescms v3.1.0 release, launch wechat applet

Road construction issues

今日睡眠质量记录77分

MySQL installation, uninstallation, initial password setting and general commands of Linux

物联网毕设 --(STM32f407连接云平台检测数据)

Elk note 24 -- replace logstash consumption log with gohangout

Some thoughts on business
随机推荐
JSP and filter
Spark实战1:单节点本地模式搭建Spark运行环境
Detailed explanation of multithreading
[colab] [7 methods of using external data]
stm32和电机开发(从mcu到架构设计)
Flink SQL knows why (17): Zeppelin, a sharp tool for developing Flink SQL
剑指 Offer 17. 打印从1到最大的n位数
Anan's doubts
Fabric. JS three methods of changing pictures (including changing pictures in the group and caching)
R语言使用data函数获取当前R环境可用的示例数据集:获取datasets包中的所有示例数据集、获取所有包的数据集、获取特定包的数据集
[Database Principle and Application Tutorial (4th Edition | wechat Edition) Chen Zhibo] [Chapter IV exercises]
Convolution emotion analysis task4
Smbms project
35道MySQL面试必问题图解,这样也太好理解了吧
双链笔记 RemNote 综合评测:快速输入、PDF 阅读、间隔重复/记忆
Cadre de logback
Slf4j log facade
Typeerror resolved: argument 'parser' has incorrect type (expected lxml.etree.\u baseparser, got type)
这本数学书AI圈都在转,资深ML研究员历时7年之作,免费电子版可看
php:&nbsp; The document cannot be displayed in Chinese