ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

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

2020-02-11 17:00:11  阅读:335  来源: 互联网

标签:Core ASP 微信 app Work Senparc 添加 public SDK


下面在 Web 空应用里展示一个简单的例子来实现发送文本消息。

本文目录:

创建 Web 空应用

命令行方式创建

dotnet new web --name ASPNETCoreWeixinWorkDemo

dotnet 是程序的名字
new 是一个子程序的名字
web 是要使用的项目模板的名字
--name ASPNETCoreWeixinWorkDemo 指定要创建的项目的名字是 WeixinWorkDemo

添加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>
    
    <ItemGroup>
        <None Update="appsettings.json">
            <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
        </None>
    </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!”消息了。

标签:Core,ASP,微信,app,Work,Senparc,添加,public,SDK
来源: https://www.cnblogs.com/Quinnz/p/12295720.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有