Author: Read more books

A few days ago, WeChat upgraded the cloud hosting in the small program developer tool to WeChat cloud hosting, adding a lot of capabilities such as OpenAPI, MySQL database, pipeline building, Web console and so on. It is quite exciting to see the documentation, which is really good news for developers, because before some business logic is mostly written in the cloud function or deployed in the server, to manage several sets. See the release of WeChat cloud hosting a little tempted to do a migration, WeChat cloud hosting compared to other modes or very advantages and prospects. WeChat cloud hosting and cloud functions as well as servers and Kubernetes. https://developers.weixin.qq.com/miniprogram/dev/wxcloudrun/src/basic/intro.html

This time I’ll take a small demo to practice. Without further ado, out of curiosity, I would like to give you a taste today:

Step 1: Open the environment

Create environment first landing WeChat cloud hosting, WeChat cloud hosting address is: https://cloud.weixin.qq.com/

First of all, I need to create an environment, which is divided into system creation and private network. Selecting the private network will list the environment that Tencent cloud account has created before corresponding to the applet. Here I choose the same environment in the private network as that used by my current applet.

This time let’s also take a look at MySQL. Compared with the previous WeChat cloud hosting, MySQL service is added, which is also very convenient to open. As shown in the figure below, it can be opened successfully in a few simple steps and supports automatic pause:

After opening is like this drip, support internal and external network access database, and provide automatic pause service, when idle help you pause.

Since the project needs to use the service of “cloud call” to obtain small program code, so here is to install the OpenAPI provided by WeChat cloud hosting. It must be noted that if the “cloud call” service is to be used, the permissions of WeChat token must be set and the interface to be used must be added to the white list.

Tips: When you use the OpenAPI interface in test development, you can open the public domain access, online environment can start the Intranet access, which is relatively safe. Because you no longer need to exchange the Access_Token for calling the OpenAPI interface as before, the public network is exposed to high risk.

Step 2: New service

Pipeline publishing

Container. Config. JSON file must be included in the pipeline distribution code. You can define the method according to the document: https://developers.weixin.qq.com/miniprogram/dev/wxcloudrun/src/basic/guide.html

Json file in the repository, and then check the other configuration. This pipeline is defined and automatically mirrored when the main branch is triggered by the code push. After you’ve built it, don’t forget to deploy the latest version at the end. Pipelines don’t automatically release the latest version for you.

release

Version release is also very convenient. After the Dockerfile is defined, it can be pulled from GitHub in Tencent Cloud Personal Warehouse Construction Configuration or the Docker image can be built locally and pushed to Tencent Cloud. I’ve chosen the WeChat cloud managed code pull:

Select the new version from the version list, pull from the code library, and pull down the program we wrote:

After pulling the code, it will automatically help us build the image in the WeChat cloud hosting. Click to view the log and you can see the detailed build process. Again, it is a familiar operation.

After the completion of the version construction, then is the release, whether you choose pipeline release or version release, the last step must choose to release online.

Step 3: Development

So let me create one here. For the Net Core project, select the WebApp template.

Next edit the Dockerfile:

#See https://aka.ms/containerfastmode to understand how Visual Studio uses this Dockerfile to build your images for Faster - was debugging. The FROM McR.microsoft.com/dotnet/aspnet:3.1 AS base WORKDIR/app EXPOSE the FROM 80 McR.microsoft.com/dotnet/sdk:3.1 AS build WORKDIR/SRC COPY [" HtArtGoWebApp. Csproj ", "."] RUN dotnet restore "./HtArtGoWebApp.csproj" COPY . . WORKDIR "/src/." RUN dotnet build "HtArtGoWebApp.csproj" -c Release -o /app/build FROM build AS publish RUN dotnet publish "HtArtGoWebApp.csproj" -c Release -o /app/publish FROM base AS final WORKDIR /app COPY --from=publish /app/publish . ENTRYPOINT ["dotnet", "HtArtGoWebApp.dll"]

Then install the database driver

< itemGroup > < packageReference Include="FreeSql" Version="2.5.200" /> < packageReference Include=" freesql.provider.mysql" Version = "2.5.200" / > < / ItemGroup >

To inject Freesql and define entities, I first define the entities. I created a new Models folder in the project, where the entities are placed. First I define a base class BaseEntity

public class BaseEntity where TKey : IEquatable { [Column(IsPrimary = true, IsIdentity = true)] public TKey Id { get; set; } [Column(ServerTime = DateTimeKind.Utc, CanUpdate = false)] public DateTime CreateTime { get; set; } [Column(ServerTime = DateTimeKind.Utc)] public DateTime UpdateTime { get; set; } public string OperatorId { get; set; } public bool IsDelete { get; set; } public bool Status { get; set; }}

Then define a class Exhibitor. cs class for testing that inherits BaseEntity, with a custom type for the primary key:

public class Exhbitions:BaseEntity { public string Title { get; set; }}

The next step is to configure and inject FreeSql in the stratup. cs file:

public Startup(IConfiguration configuration) { Configuration = configuration; // Freesql FSQL = new Freesql. FreesqlBuilder () // UseConnectionString(Freesql. Datatype.MySQL, Freesql, Freesql, Freesql) Configuration. The GetConnectionString (" MySql ")) / / open the automatic synchronization entity UseAutoSyncStructure (true) / / SQL log also open the UseMonitorCommand (CMD = > Console.WriteLine(cmd.CommandText)) .Build(); } public IConfiguration Configuration { get; } public IFreeSql fsql;

Services.addSingleton < iFreesQl >(FSQL); Services.addSingleton < iFreesQl >(FSQL);

Now that the database is configured and injected successfully, it is time to call the database to query the data. Select an index. CSHTML page to display the data query:

public class IndexModel : PageModel { private readonly ILogger _logger; private IFreeSql _freeSql; Public IList exhbitionListList {get; public IList exhbitionListList {get; set; } public IndexModel(ILogger logger,IFreeSql freeSql) { _logger = logger; _freeSql = freeSql; } public Async Task OnGetAsync() {var data = await _freeSql.Select().tolistAsync ();} public Async Task OnGetAsync() {var data = await _freeSql. ExhbitionListList = data; }}

The index. CSHTML front end is shown with a table:

<table style="margin-left: 30% "> < thead > < tr > < th > ID < / th > < th > name < / th > < th > creation date < / th > < / tr > < thead > < tbody > @ foreach (var item in this.Model.ExhbitionListList) { <tr> <td>@item.Id</td> <td>@item.Title</td> <td>@item.CreateTime</td> </tr> } </tbody> </table>

The above is the database part. Next, let’s use WeChat cloud hosted OpenAPI to make calls. The part about OpenAPI is placed in the OpenApiservice class in the RESTService folder

In this folder, I only wrote an interface to get small program code for testing. The code is as follows:

public class OpenApiService { private HttpClient _client; Public OpenApiService(HttpClient) {Client.BaseAddress =new URI (" Replace http:// with your own "); _client = client; } public async Task GetgetUnlimited() { var body = new StringContent(JsonSerializer.Serialize(new { scene = "index", page = "pages/index/index" }), Encoding.UTF8, "application/json"); var response = await _client.PostAsync("/wxa/getwxacodeunlimit", body); if (response.IsSuccessStatusCode) { MemoryStream ms = new MemoryStream(); await response.Content.CopyToAsync(ms); return ms; } return null; }}

Services.addHttpClient < OpenApiserService >(); Services.addHttpClient < OpenApiserService >(); Services.addHttpClient < OpenApiserService >();

We’ll write a Controller interface for the front end to call. Here, we’ll configure two things in STARTUP. CS:

After the configuration is done, call it in the controller:

[ApiController] [Route("api/[controller]")] public class WxController : Controller { private OpenApiService _openApiService; public WxController(OpenApiService openApiService) { _openApiService = openApiService; } [HttpGet] public async Task GetgetUnlimited() { var data = await _openApiService.GetgetUnlimited(); return new FileContentResult(data.ToArray(), "image/jpeg"); }}

Don’t forget to whitelist the interface that gets the applet code in the WeChat cloud hosting:

Well, that’s the end of the code. Debug it locally and then release it:

Get applet code normal

Database access normal

The page looks a little ugly, optimize the front page with Vue and ElementUI, introduce the related libraries for Vue and ElementUI in _layout. CSHTML, and then make the following changes in the front index. CSHTML:

public class IndexModel : PageModel { private readonly ILogger _logger; private IFreeSql _freeSql; public IList ExhbitionListList { get; set; } public IndexModel(ILogger logger,IFreeSql freeSql) { _logger = logger; _freeSql = freeSql; } // public async Task OnGetAsync() // { // var data = await _freeSql.Select().ToListAsync(); // ExhbitionListList = data; // } public async Task OnGetList() { var data = await _freeSql.Select().ToListAsync(); return new JsonResult(data); }}

Optimize the HTML page with the Table component of Element:

<div id="app"> <el-table v-bind:data="list" border style="width: > <el-table-column fixed prop="id" label="id"> </el-table-column> <el-table-column prop="title" label=" title" > </el-table-column bb0 <el-table-column prop="createTime" label=" time "> </el-table-column bb2 <el-table-column fixed="right" Width ="100"> <template slot-scope="scope"> <el-button v-on:click="handleClick(scope.row)" type="text" Size ="small"> View </el-button> <el-button type="text" size="small"> Edit </el-button> </template> </el-table-column> </el-table> </div >@section Scripts {<script type="text/javascript"> var app=new Vue({el:'#app', data:{title:' Page ', list:[] }, async created(){ const list= await this.loadData(); this.list = list }, methods:{ loadData(){ return new Promise(((resolve, reject) => $.ajax({ url:'? handler=List', success:(res)=>{ resolve(res) },fail:(err)=>{ reject(err) } }) )) }, handleClick(row) { console.log(row); }} }) </script> }

The displayed page looks like this and will be added later with CURD related actions:



Then add an API management tool Swagger. To demonstrate the simplest configuration of Swagger here, add Swagger first by installing the Swagger package Swashbuckle. AspnetCore on NuGet. Then inject Services.addSwaggerGen () into the ConfiguReservices method; , register Swagger middleware in Configure: app.useSwagger ();

app.UseSwaggerUI(c=>{c.SwaggerEndpoint(“/swagger/v1/swagger.json”, “My API V1”); });

Then access localhost: 5000 / / swagger/index. HTML

Finally, everything is normal after the release of the online, I feel that the future can be expected, the log query is also very convenient, this must be like:

conclusion

To sum up, WeChat cloud hosting is a good direction, which is very suitable for rapid development and validation of business models. I hope to support environment sharing and custom domain name as soon as possible in the later stage. There will be a second article on how to access CMS into the project

Experience immediately

Please use PC browser to access the following address: https://cloud.weixin.qq.com/ can begin to experience and enjoy the first free allowances.

Communication group