Asp. NetCore1.1 does not have project. json, so as to generate cross-platform packages, json cross-platform

Source: Internet
Author: User
Tags dotnet

Asp. NetCore1.1 does not have project. json, so as to generate cross-platform packages, json cross-platform

This chapter will share with you Asp. the project is removed from NetCore1.1. how to package and generate cross-platform packages after json. In order to better follow up the development of AspNetCore, uninstall vs2015, which was used for netcore development, and install vs2017, the direct advantage of this is to free up about 10 Gb of space for the C drive I reported red. From here, we can directly feel that vs2017 is so small; I have written an article about the open-source netcore service.Open-source cross-platform service plug-in-TaskCore. MainFormWhich describes how to generate and deploy the netcore project inWin7 and ubuntu16.04For example on the system, if you are interested, you can take a look. I hope you will like the content in this article and I hope you will enjoy it more"Support for code scanning"And"Recommendation"Thank you!

Use Session in AspNetCore (based on the MemoryCache component)

This section does not seem to conform to the title of the article. It mainly involves writing too little content to generate cross-platform packages. Some friends feel unsatisfied when they work too little, so use this to fill in sessions. Haha (my idea is to make progress every day, even a little bit). For a web program, Session storage usually has many ways, for example, in my previous article, I used Redis to store sessions. For a netcore project, the default session storage method is memorycache, which can be Startup in the project. add the following code snippet to the ConfigureServices method in the cs file:

1 services.AddDistributedMemoryCache();2 services.AddSession(b =>3 {4     b.IdleTimeout = TimeSpan.FromMinutes(1);5     b.CookieName = "MySid";6 });

Add the app in the Configure method. useSession (); session usage; when you copy the above code snippet to your program, a small light bulb will be prompted. You need to click to reference the corresponding package, for vs2017, The netcore development environment is automatically installed, so you only need to click the lightbulb to reference it. If you have not installed the Development sdk, You need to download the nuget package: Microsoft. aspNetCore. session; the first section services. addDistributedMemoryCache () is mainly used to add memorycache storage references. The AddSession method in the second section is actually related to adding sessions. Here I use two attributes:

1. IdleTimeout: sets the session expiration time;

2. CookieName: Set the key name of the sessionId stored in the client browser;

After completing the preceding steps, you can use HttpContext. Session. Set to add a session in the Action of any Controller (HomeController:

1 public IActionResult About () 2 {3 _ logger. logInformation ("About"); 4 5 var userInfo = "My NetCore Session"; 6 HttpContext. session. set (SessionKey, System. text. encoding. UTF8.GetBytes (userInfo); 7 ViewData ["Message"] = $ "read configuration file Option1 node value: {this. _ options. option1}, add session "; 8 return View (); 9}

Use HttpContext. Session. TryGetValue (SessionKey, out var bt) in the Action of another Contact to obtain the session we just set:

1 public IActionResult Contact () 2 {3 var userInfo = string. empty; 4 if (HttpContext. session. tryGetValue (SessionKey, out var bt) 5 {6 userInfo = System. text. encoding. UTF8.GetString (bt); 7} 8 9 ViewData ["Message"] = string. isNullOrWhiteSpace (userInfo )? "Empty Session retrieval": userInfo; 10 return View (); 11}

Well, it's so easy. Let's see the result by running the dontnet run Command to run the test site. The interface will get the following in case of exceptions:

On the browser console, we can see that our sessionId is named MySid, which is the same as CookieName we set in Startup. cs;

 

ISession Extension Method

The Set Method used above is used to save sesseion. Let's take a look at her parameter void Set (string key, byte [] value); key-value Pair method, however, the value is a byte [] type parameter. it is not convenient to change the data type every time we use it. We can extend the ISession by using the extension method, the extension code is as follows:

1 public static class PublicExtensions 2 {3 # region ISession extended 4 5 // <summary> 6 // set session 7 /// </summary> 8 // <typeparam name = "T"> </typeparam> 9 // <param name = "session"> </param> 10 /// <param name = "key"> </ param> 11 // <param name = "val"> </param> 12 // <returns> </returns> 13 public static bool Set <T> (this ISession session, string key, T val) 14 {15 if (string. isNullOrWhiteSpace (key) | val = null) {return false;} 16 17 var strVal = JsonConvert. serializeObject (val); 18 var bb = Encoding. UTF8.GetBytes (strVal); 19 session. set (key, bb); 20 return true; 21} 22 23 // <summary> 24 // obtain session25 // </summary> 26 // <typeparam name = "T"> </typeparam> 27 /// <param name = "session"> </param> 28 // <param name = "key"> </param> 29 // <returns> </ returns> 30 public static T Get <T> (this ISession session, string key) 31 {32 var t = default (T); 33 if (string. isNullOrWhiteSpace (key) {return t;} 34 35 if (session. tryGetValue (key, out byte [] val) 36 {37 var strVal = Encoding. UTF8.GetString (val); 38 t = JsonConvert. deserializeObject <T> (strVal); 39} 40 return t; 41} 42 43 # endregion44}

Directly transfer an object T to the extension method, convert it to the stored session, and then modify the code on the above test case for better testing. For example:

1 public IActionResult About () 2 {3 _ logger. logInformation ("About"); 4 5 // var userInfo = "My NetCore Session"; 6 // HttpContext. session. set (SessionKey, System. text. encoding. UTF8.GetBytes (userInfo); 7 8. You can call this operation to create a data synchronization task. session. set <shortname> (SessionKey, user); 10 ViewData ["Message"] = $ "read configuration file Option1 node value: {this. _ options. option1}, add session "; 11 return View (); 12} 13 14 public IA CtionResult Contact () 15 {16 // var userInfo = string. empty; 17 // if (HttpContext. session. tryGetValue (SessionKey, out var bt) 18 // {19 // userInfo = System. text. encoding. UTF8.GetString (bt); 20 //} 21 22 // ViewData ["Message"] = string. isNullOrWhiteSpace (userInfo )? "The Session is null.": userInfo; 23 24 var user = HttpContext. Session. Get <shortname> (SessionKey); 25 ViewData ["Message"] = user = null? "Session retrieval is blank": $ "nickname: {user. UserName}"; 26 return View (); 27}

It seems that the set or get session operations are completed with only one code. Is it much more convenient? The most important command is: dotnet run to test the effect, which is the same as the above;

 

How to generate cross-platform packages after project. json is removed from version 1.1

Now, the topic is displayed. For the latest netcore version, remove the project. the json discussion on the Internet is still fierce, but there is no official Chinese article about the online search. If you generate a exaggerated platform package, you may be the first one here; first, the netcore team should remove the project. after the json files are important, their tasks are stored in the project. in the csproj file, that is, the project file generated by vs. Let's take the test case above as an example. content of the csproj file:

 1 <Project Sdk="Microsoft.NET.Sdk.Web"> 2  3   <PropertyGroup> 4     <TargetFramework>netcoreapp1.1</TargetFramework> 5   </PropertyGroup> 6   <PropertyGroup> 7     <PackageTargetFallback>$(PackageTargetFallback);portable-net45+win8+wp8+wpa81;</PackageTargetFallback> 8   </PropertyGroup> 9   <ItemGroup>10     <PackageReference Include="Microsoft.ApplicationInsights.AspNetCore" Version="2.0.0" />11     <PackageReference Include="Microsoft.AspNetCore" Version="1.1.1" />12     <PackageReference Include="Microsoft.AspNetCore.Mvc" Version="1.1.2" />13     <PackageReference Include="Microsoft.AspNetCore.Session" Version="1.1.1" />14     <PackageReference Include="Microsoft.AspNetCore.StaticFiles" Version="1.1.1" />15     <PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="1.1.1" />16     <PackageReference Include="Microsoft.VisualStudio.Web.BrowserLink" Version="1.1.0" />17   </ItemGroup>18   <ItemGroup>19     <DotNetCliToolReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Tools" Version="1.0.0" />20   </ItemGroup>21 </Project>

Here we can intuitivelyItemGroupThe node displays the reference of the added Session and the reference of the Logging that comes with the Project template. The parent node Project Sdk = "Microsoft. NET. sdk. web ", to generate a cross-platform running package, you need to configure 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 we can generate the exaggerated platform package by issuing the command. Isn't that simple? So we have a Session section above to do the job? Well, let's test it, run the following command in the project root directory:Dontnet restore

Then execute your short release command (here I will execute it directly using the default parameter method, and the release package will be generated and then bin ):Dotnet publish

In this case, we can:Bin \ Debug \ netcoreapp1.1See belowPublishFolder, which contains the program execution file. To test the effect, I run the following command:Dontnet WebApp01.dll(Because I have installed the sdk here, you can run this command directly) to run my test case project:

Here a windows running package is complete, a friend began to doubt that cross-platform it, as well as your previous configuration of the <RuntimeIdentifiers> win7-x64; ubuntu.16.04-x64 </RuntimeIdentifiers> what is the effect of it, then here we start to demonstrate how to generate the runtime t.16.04-x64 package (win7-x64 is also the same way); we also need to go through:Dontnet restoreWhen the command is released later, write as follows:

Dotnet publish-f netcoreapp1.1 -- runtime ubuntu.16.04-x64

Command description:

-F:The abbreviation of framework;

Netcoreapp1.1:Is the storage folder;

-- Runtime:Required to run the command;

Ubuntu.16.04-x64:Name of the stored folder

The final result is in the directory:Debug \ netcoreapp1.1The following generatesUbuntu.16.04-x64Folder, which is the running package. If you want to generate the running package of other systems, the same operation procedure is as follows:

1. Add the corresponding Runtime command in project. csproj (for example: win7-x64; osx.10-11-x64; ubuntu.16.04-x64 );

2. In dotnet publish, change the last parameter to the corresponding Runtime command (for example, ubuntu.16.04-x64)

This article is over. I hope it will help you. Thank you for reading this article;

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.