【原創】在 ASP.NET Core 3.1 中使用 Senparc.Weixin.Work 企業微信 SDK —— 發送文本消息

下面在 Web 空應用裏展現一個簡單的例子來實現發送文本消息。web

本文目錄:
json

建立 Web 空應用

命令行方式建立

$ dotnet new web --name ASPNETCoreWeixinWorkDemo

dotnet 是程序的名字
new 是一個子程序的名字
web 是要使用的項目模板的名字
--name ASPNETCoreWeixinWorkDemo 指定要建立的項目的名字是 ASPNETCoreWeixinWorkDemo瀏覽器

添加SDK引用

命令行方式

進入項目目錄
$ cd ASPNETCoreWeixinWorkDemo

添加包引用

$ dotnet add package Senparc.Weixin.Work

這個命令的執行效果能夠在 WeixinWorkDemo.csproj 文件中看到。緩存

<Project Sdk="Microsoft.NET.Sdk.Web">

    <PropertyGroup>
        <TargetFramework>netcoreapp3.1</TargetFramework>
    </PropertyGroup>

    <ItemGroup>
      <PackageReference Include="Senparc.Weixin.Work" Version="3.7.104.2" />
    </ItemGroup>
    
</Project>

配置和使用SDK

添加appsettings.Development.json文件

aappsettings.Development.json 文件通常用做 ASP.NET Core 項目的開發環境配置文件,在 ASP.NET Core 項目中一般能夠看到。微信

文件內容以下,其中須要替換你本身的信息進去。app

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "SenparcSetting": {
    "IsDebug": true,
    "DefaultCacheNamespace": "DefaultCache"
  },
  "SenparcWeixinSetting": {
    "IsDebug": true,
    "WeixinCorpId": "替換爲你的企業微信企業ID",
    "WeixinCorpAgentId": "替換爲你的企業微信應用ID",
    "WeixinCorpSecret": "替換爲你的企業微信應用的Secret"
  }
}

修改Startup.cs,配置服務

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllers();//註冊控制器
        services.AddMemoryCache();//註冊本地緩存          
        services.AddSenparcWeixinServices(Configuration);//註冊全局微信服務
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IOptions<SenparcSetting> senparcSetting, IOptions<SenparcWeixinSetting> senparcWeixinSetting)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseRouting();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapGet("/", async context => { await context.Response.WriteAsync("Hello World!"); });
            endpoints.MapControllers();//設置路由匹配
        });

        app.UseSenparcGlobal(env, senparcSetting.Value, globalRegister => { })
            .UseSenparcWeixin(senparcWeixinSetting.Value, weixinRegister =>
            {
                weixinRegister.RegisterWorkAccount(senparcWeixinSetting.Value, "替換爲你的應用名字");//註冊企業微信
            });
    }
}

添加Controller,在Get方法中發送消息

在項目下添加Controller目錄,在目錄下添加SendMessageController.cs,添加內容以下async

using Microsoft.AspNetCore.Mvc;
using Senparc.Weixin;
using Senparc.Weixin.Work.AdvancedAPIs;
using Senparc.Weixin.Work.Containers;

namespace ASPNETCoreWeixinWorkDemo.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class SendMessageController : ControllerBase
    {
        static readonly string CorpId = Config.SenparcWeixinSetting.WorkSetting.WeixinCorpId;//經過全局對象獲取配置
        static readonly string CorpSecret = Config.SenparcWeixinSetting.WorkSetting.WeixinCorpSecret;//經過全局對象獲取配置
        static readonly string AppId = Config.SenparcWeixinSetting.WorkSetting.WeixinCorpAgentId;//經過全局對象獲取配置
        static readonly string AppKey = AccessTokenContainer.BuildingKey(CorpId, CorpSecret);//用於獲取token的標識
        
        // GET
        [HttpGet]
        public IActionResult Get()
        {
            // 經過標識獲取 access token
            var token = AccessTokenContainer.GetToken(AppKey);

            // 使用 SDK 的消息 API 發送文本信息
            MassApi.SendText(token, AppId, "Hello World!", "替換爲要發送的人員帳號");
            
            return Ok("Send Message To OK.");
        }
    }
}

而後在瀏覽器裏訪問 https://localhost:5001/SendMessage,就能夠看到頁面顯示「Send Message To OK.」,在企業微信客戶端裏就能夠看到「Hello World!」消息了。ui

相關文章
相關標籤/搜索