How to generate a cross-platform package after removing project. json from Asp. NetCore1.1,

Source: Internet
Author: User

How to generate a cross-platform package after removing project. json from Asp. NetCore1.1,

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. It is an open-source cross-platform service plug-in-TaskCore. mainForm, which describes the example of netcore project generation and deployment on win7 and ubuntu16.04 systems. If you are interested, you can check it out. The following is the content of this article, I also hope you will receive more "Scan code support" 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:

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

AndConfigureAddApp. 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, netcore is automatically installed in the development environment, 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 paragraphServices. AddDistributedMemoryCache ()The main function is to add a memorycache storage reference. The AddSession method in the second section is actually related to the session. 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 useHttpContext. Session. SetMethod to add a session:

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

And then use it in the Action of another Contact.HttpContext. Session. TryGetValue (SessionKey, out var bt)To get the session we just set:

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 )? "Empty Session retrieval": userInfo; return View ();}

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:

In the browser console, we can see that our sessionId is named MySid.Startup. csThe same CookieName is set;

ISession Extension Method

The Set Method used above is used to save sesseion. Let's take a look at her parameters.Void Set (string key, byte [] value );Key-Value Pair method, but the value is a byte [] type parameter. it is not convenient to switch the data type every time we use it, we can extend the ISession by using the extension method, as shown in the following code:

Public static class PublicExtensions {# region ISession extension // <summary> // set 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 the 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}

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:

Public IActionResult About () {_ logger. logInformation ("About"); // var userInfo = "My NetCore Session"; // HttpContext. session. set (SessionKey, System. text. encoding. UTF8.GetBytes (userInfo); shortname user = new shortname (); HttpContext. session. set <shortname> (SessionKey, user); ViewData ["Message"] = $ "read configuration file Option1 node value: {this. _ options. option1}, add 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 )? "The Session is null.": userInfo; var user = HttpContext. Session. Get <shortname> (SessionKey); ViewData ["Message"] = user = null? "Session retrieval is blank": $ "nickname: {user. UserName}"; return View ();}

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:

<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 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:

 <PropertyGroup> <RuntimeIdentifiers>win7-x64;ubuntu.16.04-x64</RuntimeIdentifiers> </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

At this time, we can see the publish folder under the Directory: bin \ Debug \ netcoreapp1.1, which contains the program execution file. To test the effect, here I use the 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 the framework;

Netcoreapp1.1: The storage folder;

-- Runtime: required to run the command;

Ubuntu.16.04-x64: name of the stored folder

The final result is that a ubuntu.16.04-x64 folder is generated under the directory Debug \ netcoreapp1.1, which contains the running package; if you want to generate the running packages of other systems, the same operation procedure is performed:

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;

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

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.