当前位置:网站首页>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 ;
边栏推荐
- Kivy教程之 如何自动载入kv文件
- In the promotion season, how to reduce the preparation time of defense materials by 50% and adjust the mentality (personal experience summary)
- Logback log framework
- 71 articles on Flink practice and principle analysis (necessary for interview)
- Internet of things completion -- (stm32f407 connects to cloud platform detection data)
- R语言使用data函数获取当前R环境可用的示例数据集:获取datasets包中的所有示例数据集、获取所有包的数据集、获取特定包的数据集
- Fabric. JS three methods of changing pictures (including changing pictures in the group and caching)
- Spark实战1:单节点本地模式搭建Spark运行环境
- 双链笔记 RemNote 综合评测:快速输入、PDF 阅读、间隔重复/记忆
- Solve system has not been booted with SYSTEMd as init system (PID 1) Can‘t operate.
猜你喜欢
![[colab] [7 methods of using external data]](/img/cf/07236c2887c781580e6f402f68608a.png)
[colab] [7 methods of using external data]
[email protected] chianxin: Perspective of Russian Ukrainian cyber war - Security confrontation and sanctions g"/>Start signing up CCF C ³- [email protected] chianxin: Perspective of Russian Ukrainian cyber war - Security confrontation and sanctions g

The 35 required questions in MySQL interview are illustrated, which is too easy to understand

PowerPoint tutorial, how to save a presentation as a video in PowerPoint?

stm32和电机开发(从mcu到架构设计)

Elk note 24 -- replace logstash consumption log with gohangout

Flink SQL knows why (19): the transformation between table and datastream (with source code)

剑指 Offer 12. 矩阵中的路径

Flink SQL knows why (XV): changed the source code and realized a batch lookup join (with source code attached)

Flink SQL knows why (12): is it difficult to join streams? (top)
随机推荐
编程内功之编程语言众多的原因
regular expression
Sword finger offer 14- ii Cut rope II
2022-01-27 use liquibase to manage MySQL execution version
Flick SQL knows why (10): everyone uses accumulate window to calculate cumulative indicators
PowerPoint tutorial, how to save a presentation as a video in PowerPoint?
Sword finger offer 14- I. cut rope
SwiftUI 开发经验之作为一名程序员需要掌握的五个最有力的原则
R language uses the data function to obtain the sample datasets available in the current R environment: obtain all the sample datasets in the datasets package, obtain the datasets of all packages, and
剑指 Offer 14- II. 剪绳子 II
mysqlbetween实现选取介于两个值之间的数据范围
When we are doing flow batch integration, what are we doing?
Setting up remote links to MySQL on Linux
2022-02-14 analysis of the startup and request processing process of the incluxdb cluster Coordinator
剑指 Offer 17. 打印从1到最大的n位数
Detailed explanation of multithreading
Mysql database basic operation - regular expression
PowerPoint 教程,如何在 PowerPoint 中将演示文稿另存为视频?
Image component in ETS development mode of openharmony application development
[Database Principle and Application Tutorial (4th Edition | wechat Edition) Chen Zhibo] [sqlserver2012 comprehensive exercise]