当前位置:网站首页>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 ;
边栏推荐
- OpenHarmony应用开发之ETS开发方式中的Image组件
- [Database Principle and Application Tutorial (4th Edition | wechat Edition) Chen Zhibo] [sqlserver2012 comprehensive exercise]
- Today's sleep quality record 77 points
- 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
- SwiftUI 开发经验之作为一名程序员需要掌握的五个最有力的原则
- mysql更新时条件为一查询
- Flink SQL knows why (13): is it difficult to join streams? (next)
- Logback log framework
- Fabric. JS three methods of changing pictures (including changing pictures in the group and caching)
- [today in history] July 3: ergonomic standards act; The birth of pioneers in the field of consumer electronics; Ubisoft releases uplay
猜你喜欢
人身变声器的原理
Setting up remote links to MySQL on Linux
2022-02-11 heap sorting and recursion
常见的几种最优化方法Matlab原理和深度分析
35道MySQL面试必问题图解,这样也太好理解了吧
OpenHarmony应用开发之ETS开发方式中的Image组件
道路建设问题
正则表达式
[colab] [7 methods of using external data]
The shortage of graphics cards finally came to an end: 3070ti for more than 4000 yuan, 2000 yuan cheaper than the original price, and 3090ti
随机推荐
SQL learning notes (I)
[Database Principle and Application Tutorial (4th Edition | wechat Edition) Chen Zhibo] [Chapter IV exercises]
Swiftui development experience: the five most powerful principles that a programmer needs to master
The shortage of graphics cards finally came to an end: 3070ti for more than 4000 yuan, 2000 yuan cheaper than the original price, and 3090ti
Kivy教程之 如何通过字符串方式载入kv文件设计界面(教程含源码)
2022-01-27 redis cluster cluster proxy predixy analysis
【电脑插入U盘或者内存卡显示无法格式化FAT32如何解决】
剑指 Offer 15. 二进制中1的个数
18W word Flink SQL God Road manual, born in the sky
Setting up remote links to MySQL on Linux
Flink code is written like this. It's strange that the window can be triggered (bad programming habits)
【R】 [density clustering, hierarchical clustering, expectation maximization clustering]
mysql更新时条件为一查询
OpenHarmony应用开发之ETS开发方式中的Image组件
2022-02-11 practice of using freetsdb to build an influxdb cluster
Anan's doubts
剑指 Offer 14- I. 剪绳子
Today's sleep quality record 77 points
Flink SQL knows why (XI): weight removal is not only count distinct, but also powerful duplication
Sword finger offer 17 Print from 1 to the maximum n digits