有没有一种方法可以使用Web API从ASP.NET网站发送短信?我知道有关Web服务的内容,但不知道如何从我的应用程序调用这些服务。
使用Web服务是最好的方法。我在一个网站上使用Twilio,而且设置和工作都非常容易。可扩展性也不成问题,你可以通过使用Twilio来代替花费开发人员时间构建自己的解决方案,从而弥补成本。
Twilio: http://www.twilio.com/
Twilio提供了.NET库:https://www.twilio.com/docs/csharp/install
以下是发送短信的示例代码(摘自twilio-csharp项目,仅为演示其易用性而转载):
static void Main(string[] args)
{
TwilioRestClient client;
// ACCOUNT_SID and ACCOUNT_TOKEN are from your Twilio account
client = new TwilioRestClient(ACCOUNT_SID, ACCOUNT_TOKEN);
var result = client.SendMessage(CALLER_ID, "PHONE NUMBER TO SEND TO", "The answer is 42");
if (result.RestException != null) {
Debug.Writeline(result.RestException.Message);
}
}
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using Twilio;
namespace TwilioSMSHowTo
{
public partial class _default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void SendMessage_OnClick(object sender, EventArgs e)
{
string ACCOUNT_SID = ConfigurationManager.AppSettings["ACCOUNT_SID"];
string AUTH_TOKEN = ConfigurationManager.AppSettings["AUTH_TOKEN"];
TwilioRestClient client = new TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN);
client.SendMessage("(502) 276-8990", ToNumber.Text, Message.Text);
}
}
}
要使此代码正常工作,您需要使用NuGet获取Twilio API,并且需要将我的configurationmanager.appsettings内容替换为您的帐户ID和身份验证令牌。
编码愉快!
如果您希望使用另一个短信服务提供商Way2Sms.com而不是Twilio API来完成这项任务,我认为以下代码可以帮助您:
public void sendsms(object sender, EventArgs e)
{
if (Page.IsValid)
{
HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create("http://ubaid.tk/sms/sms.aspx?uid=" + yourmobilenumber + "&pwd=" + yourpassword + "&msg=" + body.Text + "&phone=" + recipientNo.Text + "&provider=way2sms");
HttpWebResponse myResp = (HttpWebResponse)myReq.GetResponse();
System.IO.StreamReader respStreamReader = new System.IO.StreamReader(myResp.GetResponseStream());
string responseString = respStreamReader.ReadToEnd();
respStreamReader.Close();
myResp.Close();
}
}