【发布时间】:2017-03-09 21:12:54
【问题描述】:
我正在尝试制作一个可以使用 twilio API 发送短信的应用程序
此 API 包含 statusCallback 属性,我们可以包含一个链接,该 API 可以发送有关交付行为的数据(如果收到短信等...)
public void sendSMS()
foreach (var toNumber in TOnumbersList)
{
var message = MessageResource.Create(
to: new PhoneNumber(toNumber),
from: new PhoneNumber(fromNumber),
body: msgBody,
provideFeedback: true,
statusCallback: new Uri("http://localhost:5000/"));// <----
}
如您所见,在 statusCallback 中我明确表示我想在 localhost:5000/ 上发送信息
在我的 Visual Studio 2015 解决方案资源管理器中,我添加了一个单独的项目并将其命名为 windows 服务
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.ServiceProcess;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace WindowsService
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
static void Main()
{
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new Service1()
};
// ServiceBase.Run(ServicesToRun);
_httpListener.Prefixes.Add("http://localhost:5000/"); // add prefix "http://localhost:5000/"
_httpListener.Start(); // start server (Run application as Administrator!)
Console.WriteLine("Server started.");
Thread _responseThread = new Thread(ResponseThread);
_responseThread.Start(); // start the response thread
}
static HttpListener _httpListener = new HttpListener();
static void ResponseThread()
{
while (true)
{
HttpListenerContext context = _httpListener.GetContext(); // get a context
var a = context.Request.Url; // Now, you'll find the request URL in context.Request.Url
byte[] _responseArray = Encoding.UTF8.GetBytes("<html><head><title>Localhost server -- port 5000</title></head>" +
"<body>Welcome to the <strong>Localhost server</strong> -- <em>port 5000!</em></body></html>"); // get the bytes to response
context.Response.OutputStream.Write(_responseArray, 0, _responseArray.Length); // write bytes to the output stream
context.Response.KeepAlive = false; // set the KeepAlive bool to false
context.Response.Close(); // close the connection
Console.WriteLine("Respone given to a request.");
}
}
}
}
之后,在解决方案的配置中,我明确表示我希望服务在 windows 窗体项目之前运行,如图所示
所以一旦我启动解决方案,我就进入 localhost:5000 并注意到该服务正在运行并且页面正在显示欢迎消息
但是,一旦调用(或调用) sendSMS() 函数(在服务运行时),我就会收到此错误:
错误:本地主机上的状态回调不是有效的 URL
所以我的问题是我做错了什么?我想了解我对 Web 服务技术不是很有经验,是我忘记启用某些东西了吗?或者与异步和同步问题有关的东西?
注意:过去,(而不是使用本地主机),我使用 http://requestb.in/ 创建了一个 url(它完成了 web 服务的工作),我复制了创建的 url,发送数据没有问题在链接上。但是当链接是 localhost 时,会发现问题
【问题讨论】:
标签: c# web-services callback windows-services localhost