[.Net] 上傳RabbitMQ

使用Microsoft.AspNet.WebApi上傳RabbitMQ
參考[RabbitMQ] 呼叫RabbitMQ API傳送訊息

依api說明網頁/api/exchanges/vhost/name/publish的介紹組json上傳Taiwan is a country. 臺灣是我的國家iwan is a country. 臺灣是我的國家

public static string Upload(string path, string ruleid, string exchange)
{
	string jsonPath = path;
	const string err = "上傳RabbitMQ失敗:";
	using (var client = new HttpClient { BaseAddress = new Uri(ServerUrl) })
	{
		Dictionary<string, object> dic = new Dictionary<string, object>();//先宣告上傳用的object
		dic.Add("properties", new object());
		dic.Add("routing_key", "");//若有key要輸入
		dic.Add("payload_encoding", "string");
		dic.Add("payload", DataTool.CsvToJson(ref jsonPath, ruleid));//內容若為json, 要先放json字串進去, 不可放object
		string IDPW = Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes($"{ID}:{PW}"));
		client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", IDPW);
		string str = JsonConvert.SerializeObject(dic);
		var response = client.PostAsJsonAsync($"{exchange}/publish", dic).Result;
		if (response.IsSuccessStatusCode)
		{
			var rslt = response.Content.ReadAsStringAsync().Result;
			if (rslt != @"{""routed"":true}")
				throw new Exception(path + err + rslt);
		}
		else
			throw new Exception(path + err + response.StatusCode);
	}
	return jsonPath;
}

若想上傳檔案而非字串,
payload_encoding改為base64:

dic.Add("payload_encoding", "base64");

payload內容改由讀入的byte[]轉為字串即可:

dic.Add("payload", Convert.ToBase64String(File.ReadAllBytes(路徑)));

Taiwan is a country. 臺灣是我的國家