.net core 3.1 webapi新建与部署

1,993 阅读3分钟

1.新建

(1) 打开vs2019, 新建asp.net core web => api

(2) 删除天气controller, 和天气类,

(3) 新建api 空控制器, 添加如下代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using ApiCore.Bo.UserInfo;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using XCode.Membership;

namespace ApiCore.Controllers
{
    //[Route("api/[controller]")]
    //[ApiController]
    public class UserController : ControllerBase
    {
        readonly UserRepositofy repo = new UserRepositofy();
        [HttpGet]
        public async Task<IActionResult>  UserAdd() => Ok(await repo.UserAdd());
        [HttpGet]
        public async Task<IActionResult>  UserSearch() => Ok(await repo.UserSearch());
     

    }
}

(4) UserRepositofy代码如下

using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using XCode.Membership;

namespace ApiCore.Bo.UserInfo
{
    public class UserRepositofy
    {
        public async Task<BasPosMsg>  UserAdd()
        {
            BasPosMsg ret = new BasPosMsg();
            try
            {
                await Task.Run(() =>
                {
                    // 添加
                    var user = new UserX
                    {
                        Name = "djkgf",
                        Enable = true
                    };
                    var book = new Book
                    {
                        Name = "jsf1"
                    };

                    user.Insert();
                    book.Insert();
                    ret.Code = "200";
                    ret.Msg = "success";
                });
             
            }
            catch (Exception e)
            {

                ret.Code = "500";
                ret.Msg = e.Message;
            }
        
            return ret;
        }
        public async Task<UserSearchRet>  UserSearch()
        {
          
            UserSearchRet ret = new UserSearchRet();
            try
            {
                await Task.Run(() =>
                {

                    var userL = UserX.FindAllWithCache();
                    ret.Code = "200";
                    ret.Msg = "success";
                    foreach (UserX user in userL)
                    {
                        UserInfo userxx = new UserInfo
                        {
                            Name = user.Name,
                            Code = user.Code,
                        };
                        ret.Data.Add(userxx);
                    }

                });

            }
            catch (Exception e)
            {

                ret.Code = "500";
                ret.Msg = e.Message;
            }
            return ret;
        }

    }

}

(4) User 代码如下

using System;
using System.Collections.Generic;
using System.Text;
using XCode.Membership;

namespace ApiCore.Bo.UserInfo
{
   public  class BasPosMsg
    {
        public string Code { set; get; }
        public string Msg { set; get; }

    }
    public class UserInfo
    {
        public string Name { set; get; }
        public string Code { set; get; }
     

    }
    public class UserSearchRet: BasPosMsg
    {
        public List<UserInfo> Data { set; get; }
        public string Name { set; get; }
        public UserSearchRet()
        {
            Data = new List<UserInfo>();
        }

    }
}

(5) /ApiCore/Properties/launchSettings.json下, 修改launchUrl启动路径,便于运行项目直接显示json

{
  "$schema": "http://json.schemastore.org/launchsettings.json",
  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:26504",
      "sslPort": 0
    }
  },
  "profiles": {
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "launchUrl": "api/User/UserAdd",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
    "ApiCore": {
      "commandName": "Project",
      "launchBrowser": true,
      "launchUrl": "weatherforecast",
      "applicationUrl": "http://localhost:5000",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
  }
}

(6) Startup中增加全局路由

  app.UseEndpoints(endpoints =>
            {
                //endpoints.MapControllers();
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "api/{controller=Home}/{action=Index}/{id?}"
                    );
            });

从上到下的项目类型依次为

.net core 3.1 webapi

.net core 类库

.net core类库

.net framework 4.6.1 类库

2.发布到linux 64位(centos ubuntu都可以)

(1.) 安装 jexus

curl jexus.org/release/x64… sh

jexus常用命令

Jexus包括如下操作命令(首先 cd /usr/jexus):
启动:sudo ./jws start
停止:sudo ./jws stop
重启:sudo ./jws restart

(2.)安装 .net core 3.1 微软.net core 3.1 centos

sudo rpm -Uvh packages.microsoft.com/config/cent…

sudo yum install dotnet-sdk-3.1

sudo yum install aspnetcore-runtime-3.1

sudo yum install dotnet-runtime-3.1

dotnet --version //是否安装成功

(3) scp或者其他远程客户端, 发送压缩包publish.rar到远程服务器 /var/www目录

(4) rar x publish.rar 解压

(5) cd publish && dotnet ApiCore.dll // 程序是否正常 ,默认运行在5000端口

(6) vim /user/jexus/siteconf/default 修改如下

######################
# Web Site: Default
########################################

port=8080
root=/ /var/www/publish/
hosts=*    #OR your.com,*.your.com

# User=www-data

# AspNet.Workers=2  # Set the number of asp.net worker processes. Defauit is 1.

# addr=127.0.0.1
# CheckQuery=false
NoLog=true

 AppHost={cmd=dotnet /var/www/publish/ApiCore.dll; root=/var/www/publish; port=5000}

# NoFile=/index.aspx
# Keep_Alive=false
# UseGZIP=false

# UseHttps=true

(7) 注意, 8080端口, 需要在阿里云或其他云服务器上开启出入站规则,才可以正常使用, 配置的AppHost port = 5000 无需修改, .net core网站默认监听在5000端口

(8) 打开http://*:8080/api/user/usersearch 即可看到json数据, 也可以使用PostMain等工具测试

(9) 注意, 接口地址 /user/usersearch 或者 /User/UserSearch都是可以的,.net core 3.0 会将返回的json字段进行小驼峰命名

4. 本项目是net core 与 nfx 混合类库项目, 尽量在windows下运行

本项目运行环境

vs2019

sqlite数据库及驱动

.net core 3.1

3. 参考资料

(1) NewLife.X 中通架构师优秀的net orm 框架

(2) 新建项目参考简书地址

(3) jexus 高性能国产net 服务器

(4) centos安装.net core 3.1

(5)centos5.7下使用jexus 部署.net core