asp.net core 阿里云消息服务(Message Service,原MQS)发送接口的实现

asp.net core 阿里云消息服务(Message Service,原MQS)发送接口的实现最近在后台处理订单统计等相关功能用到了大力的mqs,由于官方没有实现asp.netcore的sdk,这里简单实现了发送信息的功能,有兴趣的可以参考实现其他相关功能usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Net.Http;usingSystem.Net.Http.Headers;…

大家好,又见面了,我是你们的朋友全栈君。如果您正在找激活码,请点击查看最新教程,关注关注公众号 “全栈程序员社区” 获取激活教程,可能之前旧版本教程已经失效.最新Idea2022.1教程亲测有效,一键激活。

Jetbrains全家桶1年46,售后保障稳定

最近在后台处理订单统计等相关功能用到了大力的mqs,由于官方没有实现asp.net core的sdk,这里简单实现了发送信息的功能,有兴趣的可以参考实现其他相关功能

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace Iyibank.Aliyun.MNS
{

public class MQHelper
{

private string url;
private string accessKeyId;
private string accessKeySecret;

private string host;
private string version = “2015-06-06”;

public MQHelper(string url, string accessKeyId, string accessKeySecret)
{

this.url = url;
this.accessKeyId = accessKeyId;
this.accessKeySecret = accessKeySecret;

this.host = url.StartsWith(“http://”) ? url.Substring(7) : url;

}
/// <summary>
/// URL 中的 Key,Tag以及 POST Content-Type 没有任何的限制,只要确保Key 和 Tag 相同唯一即可
/// </summary>
/// <param name=”tag”></param>
/// <param name=”body”></param>
/// <returns></returns>
public async Task<bool> Pub(string name, string body)
{

try
{

using (HttpClient httpClient = new HttpClient())
{

Dictionary<string, string> headers = new Dictionary<string, string>();
headers.Add(“Host”, this.host);
headers.Add(“Date”, DateTime.Now.ToUniversalTime().ToString(“r”));
headers.Add(“x-mns-version”, this.version);
headers[“Content-Type”] = “text/xml”;
string url = string.Format(“{0}/{1}”, name, “messages”);
headers.Add(“Authorization”, this.authorization(“POST”, headers, string.Format(“{0}”, “/queues/” + name + “/messages”)));

foreach (var kv in headers)
{

if (kv.Key != “Content-Type”)
{

httpClient.DefaultRequestHeaders.Add(kv.Key, kv.Value);
}

}
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(“application/xml”));
StringBuilder sb = new StringBuilder();
sb.Append(” <Message> “);
sb.Append(“<MessageBody>” + Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(body)) + “</MessageBody> “);
sb.Append(“<DelaySeconds>0</DelaySeconds> “);
sb.Append(” <Priority>1</Priority>”);
sb.Append(“</Message>”);
HttpContent content = new StringContent(sb.ToString());
content.Headers.ContentType = new MediaTypeHeaderValue(“text/xml”);
httpClient.DefaultRequestHeaders.Connection.Add(“keep-alive”);
var res = await httpClient.PostAsync(this.url + “/” + string.Format(“queues/{0}/{1}”, name, “messages”), content);
if (res.StatusCode == System.Net.HttpStatusCode.Created)
{

return true;
}
return false;
}
}
catch { return false; }
}
/// <summary>
/// 生成验证信息
/// </summary>
/// <param name=”method”></param>
/// <param name=”headers”></param>
/// <param name=”resource”></param>
/// <returns></returns>
private string authorization(string method, Dictionary<string, string> headers, string resource)
{

return string.Format(“MNS {0}:{1}”, this.accessKeyId, this.signature(“POST”, headers, resource));
}
/// <summary>
/// 签名
/// </summary>
/// <param name=”method”></param>
/// <param name=”headers”></param>
/// <param name=”resource”></param>
/// <returns></returns>
private string signature(string method, Dictionary<string, string> headers, string resource)
{

List<string> toSign = new List<string>();
toSign.Add(method.ToString());
toSign.Add(headers.ContainsKey(“Content-MD5”) ? headers[“Content-MD5”] : string.Empty);
toSign.Add(headers.ContainsKey(“Content-Type”) ? headers[“Content-Type”] : string.Empty);
toSign.Add(headers.ContainsKey(“Date”) ? headers[“Date”] : DateTime.Now.ToUniversalTime().ToString(“r”));

 

foreach (KeyValuePair<string, string> header in headers.Where(kv => kv.Key.StartsWith(“x-mns-“)).OrderBy(kv => kv.Key))
{

toSign.Add(string.Format(“{0}:{1}”, header.Key, header.Value));
}

toSign.Add(resource);

HMACSHA1 hmac = new HMACSHA1(Encoding.UTF8.GetBytes(this.accessKeySecret));
string key = string.Join(“\n”, toSign);
var hashBytes = hmac.ComputeHash(Encoding.UTF8.GetBytes(string.Join(“\n”, toSign)));
return Convert.ToBase64String(hashBytes);
}
}
}

转载于:https://www.cnblogs.com/zhangkjun/p/6143381.html

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/222978.html原文链接:https://javaforall.net

(0)
上一篇 2025年7月1日 下午2:43
下一篇 2025年7月1日 下午3:15


相关推荐

  • 小米如何安装magisk和太极阳(纯小白篇)

    小米如何安装magisk和太极阳(纯小白篇)首先说明,我本人也是一个小白,很多专业术语和知识都不是特别了解。所以如果教程里有些许错误请见谅。我自己的手机是MI8,MIUI10.x.x.,在我安装msgisk的时候看了很多经验贴才下手的最后一次成功,但是网上并没有一篇完全适合小白的帖子,所以我这个小白就站出来了。好了,下面是正文,有关刷magisk的所有软件,下面都会在用到的地方给出。建议动手之前,先通看一遍本文,然后再按照本文操作。然后你会…

    2022年6月4日
    158
  • evicted Pod

    evicted PodapiVersion:v1kind:Podmetadata:annotations:checksum/config:8476fd6406a3cc87e5471154d85fd7c50e6a629acda16989a09a5d90937bb5b0cni.projectcalico.org/podIP:192.168.1.233/32creationTimestamp:”2019-09-22T06:26:34Z”generateName:test-ap…

    2022年5月13日
    42
  • 回归分析(stata实例详细解答过程)[通俗易懂]

    回归分析(stata实例详细解答过程)[通俗易懂]现有某电商平台846条关于婴幼儿奶粉的销售信息,每条信息由11个指标组成。其中,评价量可以从一个侧面反映顾客对产品的关注度。请对所给数据进行以下方面的分析,要求最终的分析将不仅仅有益于商家,更有益于宝妈们为宝贝选择适合自己的奶粉。(1)以评价量为因变量,分析其它变量和评价量之间的关系。(2)以评价量为因变量,研究影响评价量的重要因素。我们运用stata软件解决此问题。第一问在第一问中要求我们,以评价量为因变量,分析其它变量和评价量之间的关系。我们在这里用回归分析,…

    2022年8月30日
    5
  • 从踩坑到起飞:OpenClaw 本地化部署全攻略(Windows+WSL Linux 多节点实战避坑指南)

    从踩坑到起飞:OpenClaw 本地化部署全攻略(Windows+WSL Linux 多节点实战避坑指南)

    2026年3月13日
    4
  • C的TimeSpan介绍

    C的TimeSpan介绍TimeSpan 结构 表示一个时间间隔 nbsp 它含有以下四个构造函数 TimeSpan Int64 将 nbsp TimeSpan 结构的新实例初始化为指定的刻度数 DateTime Tick 是计算机的一个计时周期 单位是一百纳秒 即一千万分之一秒 TimeSpan Int32 Int32 Int32 将 nbsp TimeSpan 结构的新实例初始化为指定的小时数 分钟数和秒数 TimeSp

    2026年3月18日
    2
  • 虚拟机linux快捷键,虚拟机控制与Linux快捷键

    虚拟机linux快捷键,虚拟机控制与Linux快捷键虚拟机的控制 在主界面打开虚拟机 start 开启 desktop 虚拟机 view 显示虚拟机 poweroff 关闭虚拟机 reset 重置虚拟机如果没有开启 不能直接 view 已经开启 再开启会报错 语言调整 Applications gt systemtools gt settings gt Region amp language gt l

    2026年3月16日
    2

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号