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


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

本文目錄:

創建 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 項目中通常可以看到。

文件內容如下,其中需要替換你自己的信息進去。

{
  "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,添加內容如下

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!”消息了。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM