![]() Главная страница Случайная страница КАТЕГОРИИ: АвтомобилиАстрономияБиологияГеографияДом и садДругие языкиДругоеИнформатикаИсторияКультураЛитератураЛогикаМатематикаМедицинаМеталлургияМеханикаОбразованиеОхрана трудаПедагогикаПолитикаПравоПсихологияРелигияРиторикаСоциологияСпортСтроительствоТехнологияТуризмФизикаФилософияФинансыХимияЧерчениеЭкологияЭкономикаЭлектроника |
SmsNotify
В этой главе рассмотрим взаимодействие с помощью смс, а не только почты. Но есть ньюанс – доступ к рассылке предоставляется отдельными сервисами, и тут мы рассмотрим только основные принципынаписания модуля для работы с SMS-провайдерами на примере работы с unisender.ru. Создадим класс настроек по типу MailSetting (/Global/Config/SmsSetting.cs): public class SmsSetting: ConfigurationSection { [ConfigurationProperty(" apiKey", IsRequired = true)] public string APIKey { get { return this[" apiKey" ] as string; } set { this[" apiKey" ] = value; } }
[ConfigurationProperty(" sender", IsRequired = true)] public string Sender { get { return this[" sender" ] as string; } set { this[" sender" ] = value; } }
[ConfigurationProperty(" templateUri", IsRequired = true)] public string TemplateUri { get { return this[" templateUri" ] as string; } set { this[" templateUri" ] = value; } } } Зададим в Web.Config (Web.config): < configSections> … < section name=" smsConfig" type=" LessonProject.Global.Config.SmsSetting, LessonProject" /> < /configSections> … < smsConfig apiKey=" *******" sender=" Daddy" templateUri=" https://api.unisender.com/ru/api/sendSms" /> < /configuration> Создадим класс SmsSender (/Tools/Sms/SmsSender.cs): public static class SmsSender { private static IConfig _config;
public static IConfig Config { get { if (_config == null) { _config = (DependencyResolver.Current).GetService< IConfig> ();
} return _config; } }
private static NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
public static string SendSms(string phone, string text) { if (! string.IsNullOrWhiteSpace(Config.SmsSetting.APIKey)) { return GetRequest(phone, Config.SmsSetting.Sender, text); } else { logger.Debug(" Sms \t Phone: {0} Body: {1}", phone, text); return " Success"; } }
private static string GetRequest(string phone, string sender, string text) { try { HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(Config.SmsSetting.TemplateUri); /// important, otherwise the service can't desirialse your request properly webRequest.ContentType = " application/x-www-form-urlencoded"; webRequest.Method = " POST"; webRequest.KeepAlive = false; webRequest.PreAuthenticate = false;
string postData = " format=json& api_key=" + Config.SmsSetting.APIKey + " & phone=" + phone + " & sender=" + sender + " & text=" + HttpUtility.UrlEncode(text); var ascii = new ASCIIEncoding(); byte[] byteArray = ascii.GetBytes(postData); webRequest.ContentLength = byteArray.Length; Stream dataStream = webRequest.GetRequestStream(); dataStream.Write(byteArray, 0, byteArray.Length); dataStream.Close();
WebResponse webResponse = webRequest.GetResponse();
Stream responceStream = webResponse.GetResponseStream(); Encoding enc = System.Text.Encoding.UTF8; StreamReader loResponseStream = new StreamReader(webResponse.GetResponseStream(), enc);
string Response = loResponseStream.ReadToEnd(); return Response; } catch (Exception ex) { logger.ErrorException(" Ошибка при отправке SMS", ex); return " Ошибка при отправке SMS"; } } } Результат приходит типа: {" result": {" currency": " RUB", " price": " 0.49", " sms_id": " 1316886153.2_79859667475" }} Его можно разобрать и проанализировать. В следующем уроке мы рассмотрим, как работать с json.
|