.net core 開發幫助

環境安裝   ::::==>Anchor 不能使用, 所以頁面內導航移除

  注意安裝64bit版本, 否則會不能用debug功能

插件安裝(VS Code中直接搜索安裝即可)

 

Step by step Demo:

1.    Hello world Demo

2.    MVC Demo

3.    Web API Demo

4.    Entity Framework 之Data First

5.    Entity Framework之Code First

6.    Angular Demo

 

IIS 部署

Linux 部署

 

 

 

 

環境安裝<<Anchor can not be used in this editor...>>

相關安裝下載

https://www.microsoft.com/net/download/all

注意安裝64bit版本, 否則會不能用debug功能,微軟暫時沒有計劃為VS Code提供此功能

Dot Net Core介紹

https://docs.microsoft.com/zh-tw/dotnet/core/

Donet指令介紹

https://docs.microsoft.com/en-us/dotnet/core/tools/?tabs=netcore2x

 

 

安裝指南

1.SDK安裝, 安裝完就可以透過命令行進行build程式了

https://www.microsoft.com/net/learn/get-started/windows

2.VS Code安裝, 微軟發起的一個免費的跨平台的Source Code編輯工具

https://code.visualstudio.com/

 

插件安裝

缺少豐富的插件的話, VS Code只是一個寫字板, 有了必要插件后可以進行代碼格式化, 查找引用, Debug 等高級編輯器才有的功能,下面是.net 用戶常見plugin.


 

Hello World Demo

正常情況下安裝完SDK后可以在命令行中直接運行dotnet指令, 如果不能運行,請將安裝dotnet 這個位置加到path環境變量

運行dotnet -h可以得到很多幫助,參考“Donet 指令介紹”

https://docs.microsoft.com/en-us/dotnet/csharp/quick-starts/

 

1.     Open a newcommand prompt and run the following commands.

      dotnet newconsole -o myApp

   cd myApp

The dotnet command willcreate a new application of type console for you. The -o parameterwill create a directory named myApp where yourapp will be stored, and populates it with the required files. The cd myApp command puts you into the newly created app directory.

The main file in the myApp folder is Program.cs. By default,it already contains the necessary code to write "Hello World!" to theConsole.

using System;

namespace myApp

{

    class Program

    {

        static voidMain(string[] args)

        {

            Console.WriteLine("HelloWorld!");

        }   

   }

}

2. Run your app

In your command prompt, run thefollowing command:

dotnet run

Congratulations, you've built and runyour first .NET app!

 


 

MVC Demo

命令行運行指令, VS Code中也一樣操作

dotnet newmvc -n YourProjectName

http://www.cnblogs.com/paluano/p/7282792.html

VSCode在“檢視View—>整合式終端機  就可以找到命令行整合小窗口

用快捷鍵 CTL+`(鍵盤上的左上角 ~ 那個按鍵,不是單撇)也可以直接叫出命令行小窗口

 


 

WebAPI Demo

dotnet newwebapi -n YourProjectName

其他同MVCweb程式類似

 

 


 

Entity Framework Data First

http://blog.csdn.net/Michel4Liu/article/details/77986731?locationNum=3&fps=1

就是先設計DB Table然後用DB Table直接產生 Entity

截止到2018/03/22 Oracle.net core driver 還是剛放出beta版本,也不支持Entity framework core, 所以請不要去用oracle折磨自己

下面例子以PostgreSQLDB 為例

1.DB中建立若干Table注意都要有Primary Key

2.新建一個DLL project或者web project 都可以

3.添加引用,建議用nuget .net core下用dotnet add package指令, 或在Project文件中添加引用后,dotnet restore指令取得引用到本地.

Microsoft.EntityFrameworkCore

Npgsql.EntityFrameworkCore.PostgreSQL

Microsoft.EntityFrameworkCore.Tools

Microsoft.EntityFrameworkCore.Design

Npgsql.EntityFrameworkCore.PostgreSQL.Design

 

 

<ItemGroup>

<PackageReferenceInclude="Microsoft.EntityFrameworkCore.Tools"Version="2.0.1"PrivateAssets="All"/>

    <PackageReferenceInclude="Microsoft.VisualStudio.Web.CodeGeneration.Design"Version="2.0.1"PrivateAssets="All"/>

        <DotNetCliToolReferenceInclude="Microsoft.EntityFrameworkCore.Tools.DotNet"Version="2.0.0"/>

    <DotNetCliToolReferenceInclude="Microsoft.Extensions.SecretManager.Tools"Version="2.0.0"/>

    <DotNetCliToolReferenceInclude="Microsoft.VisualStudio.Web.CodeGeneration.Tools"Version="2.0.0"/>

    <PackageReferenceInclude="Npgsql.EntityFrameworkCore.PostgreSQL"Version="2.0.1"/>

    <PackageReferenceInclude="Npgsql.EntityFrameworkCore.PostgreSQL.Design"Version="*"/>

</ItemGroup>

 

 

3.     Project目錄下的命令行,VS code 打開project ,用整合式終端機,運行Entity產生工具, 命令

dotnetef dbcontext scaffold "Server=XXXX;database=XXXX;uid=XXX;pwd=XXX"" Npgsql.EntityFrameworkCore.PostgreSQL" -o Entity

將會把Table轉換為Entity Clas 放到 Entity目錄下

4.    然後就可以直接用DBContext訪問數據庫了, 賬號密碼在Context文件中,你可以修改那個文件從config 中取賬號密碼

static void Main(string[] args)

    {

       Console.WriteLine("Hello World!");

       ZSAUTHDBContext db = new ZSAUTHDBContext();

        var l =db.AppLogs.Where(t=>t.AppLogId==100L).FirstOrDefault();

       Console.WriteLine(l.MessageText);

 

       db.Dispose();

        }

}

 

 


 

Code First

就是以代碼去產生數據庫

http://blog.csdn.net/aojiancc2/article/details/76615653

1.  新增或打開一個Project

2.    添加必要的packageDB First一樣

3.    編寫必要的Entity Class, 以及DB Context Class

4.    Entity sample

    

public class User

    {

        public intId { get; set; }

        publicstring Name { get; set; }

        publicstring DisplayName { get; set; }

        publicstring Description { get; set; }

        public boolRequired { get; set; }

        public boolEmphasize { get; set; }

        public boolShowInDiscoveryDocument { get; set; } = true;

        publicList<ApiScopeClaim> UserClaims { get; set; }

 

        publicApiResource ApiResource { get; set; }

    }

5.    DB Context Sample

public class MyDataContext : DbContext 

 {   
     publicMyDataContext(DbContextOptions<MyDataContext> options) :base(options) 
     { 
     } 
     publicDbSet<User> Users { get; set; } 
  protectedoverridevoidOnModelCreating(ModelBuilder modelBuilder)
        {
           modelBuilder.ConfigureClientContext(storeOptions);
           modelBuilder.ConfigureResourcesContext(storeOptions);

           // Lower TableNames
           modelBuilder.Model.GetEntityTypes()
           .Select(e => e.Relational())
           .ToList()
           .ForEach(t => t.TableName = t.TableName.ToLower()
           );

            // Lowercolumn names
           modelBuilder.Model.GetEntityTypes()
           .SelectMany(e => e.GetProperties())
           .ToList()

           .ForEach(p => p.Relational().ColumnName = p.Name.ToLower()
           );       
   
            base.OnModelCreating(modelBuilder);
        }
 }

6.    在啟動程式中注入DB Context的配置

public voidConfigureServices(IServiceCollection services) 

     { 

         // Add framework services.   
         //添加ef的依赖 
         var connection = "DB連接字符串"; 
         services.AddDbContext<MyDataContext>(options => options.UseNpgsql(connection));   
         services.AddMvc(); 
     } 

7.    執行Table產生的功能指令

dotnet ef migrations add Migration名字 c DBContext名字

dotnet ef database update --context DBContext名字

8.    確認table有產生

9.    DBFirst一樣,可以用DBContext訪問數據庫存取, 當然可以將DB Context以及其他自己開發的Service注入到MVC Controller中使用,關於注入Injection參考

https://docs.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection

 

注意:因為PostgreSQL區分大小寫,所以建議在OnModelCreating中強制對產生的Table name, column name都轉換為小寫, 避免在寫sql時因為區分大小寫而造成一定要用雙引號.

 

 

 

 

 

 

 

 

 

AngularDemo

Angular程式編寫跟.netcore沒關係, 只是放在這裡供參考, Angular 要訪問的業務邏輯要.net coreWeb API

運行下面指令可以產生前端Angular、後端.net project 目錄layout以及sample code

dotnet new angular

Angular.net webapi功能編寫在此不表。

Angular參考,注意要用Chrome瀏覽器,其他瀏覽器可能不完全兼容, AngularGoogle在維護

https://angular.cn/tutorial

https://www.w3cschool.cn/angular2/

 

 


 

IIS部署

https://www.cnblogs.com/donaldtdz/p/7802096.html

.net core的運行環境與舊的.net framework runtime 不一樣, 不再依賴于windows特有的OS API可以跨平台,所以.net core runtime需要單獨安裝.

.net coreweb程式可以直接運行監聽程式,放在IIS可以用到IIS的一些附加功能, 所以實際上IIS 是在做轉發請求

1.应用程序发布。

2.IIS上新建网站。

3.应用程序池选择无托管代码。

4.服务器上安装DotNetCore.1.0.1-WindowsHosting。選最新版

安装成功后重启服务器。

在命令程序中输入 net stop was /y 停止服务

netstart w3svc重启服务。

5.     安装 dotnet-sdk-2.0.0-win-gs-x64 選最新版

6.    如果出現運行環境不兼容的問題,Project發佈前修改project文件

<PropertyGroup>
    <TargetFramework>netcoreapp2.0</TargetFramework>
   <PublishWithAspNetCoreTargetManifest>false</PublishWithAspNetCoreTargetManifest>
</PropertyGroup>

 

 


 

Linux部署

1.  先以指定的target平台及版本dotnetpublish產生發佈的dll

2.  dll copyhost 目錄, 運行dotnetyouApp.dll即可運行

支持.netcore 的跨平台Web Host KestrelHttpServer

直接是dotnet youApp.dll 就可以host,建議設置成linuxservice,并用nginx或apache轉發

 

Nginxwith Kestrel

https://docs.microsoft.com/en-us/aspnet/core/host-and-deploy/linux-nginx?tabs=aspnetcore2x

Apachewith Kestrel

https://docs.microsoft.com/en-us/aspnet/core/host-and-deploy/linux-apache?tabs=aspnetcore2x

 

安裝SDKforLinux注意版本,以下為redhat

https://www.microsoft.com/net/learn/get-started/linux/rhel

支持的Linux版本

https://docs.microsoft.com/en-us/dotnet/core/linux-prerequisites?tabs=netcore2x

Build for docker

https://docs.microsoft.com/en-us/dotnet/core/docker/

發佈一個self-hosted Web Application

dotnet publish -c release -r linux-x64 -o selfcontained-linux-x64

./selfcontained-linux-x64/dotnetapp

 

Kestrel WebServer

https://docs.microsoft.com/en-us/aspnet/core/fundamentals/servers/kestrel?tabs=aspnetcore2x

 

You can useKestrel by itself or with a reverse proxy server, such as IIS,Nginx, or Apache. A reverse proxy server receives HTTP requests from theInternet and forwards them to Kestrel after some preliminary handling.



Either configuration — with or without a reverse proxy server — can alsobe used if Kestrel is exposed only to an internal network.

A scenario that requires a reverse proxy is when you have multipleapplications that share the same IP and port running on a single server. Thatdoesn't work with Kestrel directly because Kestrel doesn't support sharing thesame IP and port between multiple processes. When you configure Kestrel tolisten on a port, it handles all traffic for that port regardless of hostheader. A reverse proxy that can share ports must then forward to Kestrel on aunique IP and port.

Even if a reverse proxy server isn't required, using one might be a goodchoice for other reasons:

·        It can limit your exposed surface area.

·        It provides an optional additional layer of configurationand defense.

·        It might integrate better with existing infrastructure.

·        It simplifies load balancing and SSL set-up. Only yourreverse proxy server requires an SSL certificate, and that server cancommunicate with your application servers on the internal network using plainHTTP.

 





  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值