1.App和推送平台联系,创建推送通道.(30天过期,建议每次启动申请)
PushNotificationChannel pushNotificationChannel = await PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync(); pushNotificationChannel.PushNotificationReceived += PushNotificationChannel_PushNotificationReceived; private void PushNotificationChannel_PushNotificationReceived(PushNotificationChannel sender, PushNotificationReceivedEventArgs args) { if (args.NotificationType == PushNotificationType.Toast) { ToastNotificationManager.CreateToastNotifier().Show(args.ToastNotification); } }
参考 https://docs.microsoft.com/zh-cn/previous-versions/windows/apps/hh465412(v=win.10) 的备注内容,以及注意事项
2.用你的云服务器获取WNS的token认证
[DataContract] public class OAuthToken { [DataMember(Name = "access_token")] public string AccessToken { get; set; } [DataMember(Name = "token_type")] public string TokenType { get; set; } } private OAuthToken GetOAuthTokenFromJson(string jsonString) { using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(jsonString))) { var ser = new DataContractJsonSerializer(typeof(OAuthToken)); var oAuthToken = (OAuthToken)ser.ReadObject(ms); return oAuthToken; } } protected OAuthToken GetAccessToken(string secret, string sid) { var urlEncodedSecret = HttpUtility.UrlEncode(secret); var urlEncodedSid = HttpUtility.UrlEncode(sid); var body = String.Format("grant_type=client_credentials&client_id={0}&client_secret={1}&scope=notify.windows.com", urlEncodedSid, urlEncodedSecret); string response; using (var client = new WebClient()) { client.Headers.Add("Content-Type", "application/x-www-form-urlencoded"); response = client.UploadString("https://login.live.com/accesstoken.srf", body); } return GetOAuthTokenFromJson(response); }
secret和Sid前往仪表板获取,参考
https://docs.microsoft.com/zh-cn/previous-versions/windows/apps/hh465407(v=win.10)
得到access_token ,就可以向WNS发送推送请求.示例:
请求头要包含(token)
HttpClient httpClient2 = new HttpClient(); HttpRequestMessage httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, new Uri(ChannelUrl)); httpRequestMessage.Headers.Add("Authorization", "Bearer " + access_token); httpRequestMessage.Headers.Add("X-WNS-Type", "wns/toast"); string toastContent = @" <toast> <visual> <binding template='ToastGeneric'> <text>Hello World!</text> <text>This is the first Example!</text> </binding> </visual> </toast>"; HttpStringContent httpStringContent = new HttpStringContent(toastContent); httpStringContent.Headers["Content-Type"] = "text/xml"; httpStringContent.Headers["Content-Length"] = Encoding.UTF8.GetBytes(toastContent.ToCharArray()).Length.ToString(); httpRequestMessage.Content = httpStringContent; var response2 = await httpClient.SendRequestAsync(httpRequestMessage);