微信支付或退款后會發(fā)一個通知給商戶設定的不帶參數(shù)的API, 從這個功能聯(lián)想到用.net core肯定也可以一個接口向另一個接口發(fā)送數(shù)據(jù)谣蠢,試了一下储狭,果然行,用這個方法日后可以實現(xiàn)很多有用的功能。
后端C# .net core代碼:
/// <summary>
/// 發(fā)送post數(shù)據(jù)到指定接口
/// </summary>
/// <param name="postContent"></param>
/// <param name="url"></param>
/// <returns></returns>
[HttpPost]
public string PostData(string postContent, string url)
{
var respStr = string.Empty;
var k = PayHelper.MD5(key);
using (WebClient webClient = new WebClient())
{
var data = Encoding.UTF8.GetBytes((String)postContent);
var response = webClient.UploadData(url, data);
respStr = Encoding.UTF8.GetString(response);
}
return respStr;
}
/// <summary>
/// 接收通知數(shù)據(jù)
/// </summary>
[HttpPost]
public async Task<string> DataNotify()
{
string sourceStr = string.Empty ;
var request = this.HttpContext.Request;
request.EnableBuffering();
var stream = this.HttpContext.Request.Body;
using (var reader = new StreamReader(stream, Encoding.UTF8))
{
sourceStr = await reader.ReadToEndAsync();
request.Body.Position = 0;
}
return sourceStr;
}
前端試調用jQuery代碼:
$.ajax({
url: "/Work/PostData",
dataType: "text",
type: "POST",
data: {
postContent: `江山如畫晴埂,一時多少豪杰`, url: "https://localhost:44351/work/DataNotify"},
success: res => {
console.log(res);
},
error: err => {
console.log(err);
}
})
(易國軒 2020-07-17)