C# SqlServer中插入的Http侦听器与Web Api
我正在使用一个非常简单的软件。我只需要通过手机在本地计算机上发送一个查询(通过wifi),然后应用程序执行我的查询 我找到了两种方法,但我不知道哪一种更符合我的需要。 我将描述的两种方法都在我的计算机中本地运行 方法一Http侦听器: 此方法正在本地计算机上以*.exe或cmd或windows服务的形式运行 方法2 Asp Net Web Api:(我正在创建一个名为InsertData的控制器) 我注意到asp net比http侦听器慢几毫秒。但它似乎更稳定,代码更短。另外,asp net作为*.exe或cmd或windows服务通过IIS7和httplistener运行。C# SqlServer中插入的Http侦听器与Web Api,c#,asp.net-mvc,asp.net-web-api,httplistener,C#,Asp.net Mvc,Asp.net Web Api,Httplistener,我正在使用一个非常简单的软件。我只需要通过手机在本地计算机上发送一个查询(通过wifi),然后应用程序执行我的查询 我找到了两种方法,但我不知道哪一种更符合我的需要。 我将描述的两种方法都在我的计算机中本地运行 方法一Http侦听器: 此方法正在本地计算机上以*.exe或cmd或windows服务的形式运行 方法2 Asp Net Web Api:(我正在创建一个名为InsertData的控制器) 我注意到asp net比http侦听器慢几毫秒。但它似乎更稳定,代码更短。另外,asp net作为
但在我的案例中,哪种方法更稳定、更可靠?我只需要发送简单的字符串。对于用于学习的个人/本地应用程序,请选择任何一个实现速度更快的应用程序。HttpListener方法没有任何infra依赖项。而对于ASP.NET MVC WebAPi,您需要将其托管在某个地方(自托管-->HttpListener或IIS)。因此,对于简单字符串,最好使用HttpListener?
HttpListener listener;
Thread t;
private void Form1_Load(object sender, EventArgs e)
{
t = new Thread(new ThreadStart(MyThreadMethod));
t.IsBackground = true;
listener = new HttpListener();
listener.Prefixes.Add("http://192.168.0.214:8282/");
listener.Start();
t.Start();
}
void MyThreadMethod()
{
while (true)
{
IAsyncResult result = listener.BeginGetContext(new AsyncCallback(ListenerCallback), listener);
result.AsyncWaitHandle.WaitOne(30000);
}
}
public void ListenerCallback(IAsyncResult result)
{
string Response = "";
try
{
HttpListener listener = (HttpListener)result.AsyncState;
HttpListenerContext context = listener.EndGetContext(result);
var SqlData = new StreamReader(context.Request.InputStream,context.Request.ContentEncoding).ReadToEnd();
string connectionString = "Server=(local);Database=xxxx;User id=admin;password=1234;";
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
using (SqlCommand ReceiveData = new SqlCommand(SqlData, connection))
ReceiveData.ExecuteNonQuery();
Response = "OK";
}
HttpListenerResponse response = context.Response;
string responseString = Convert.ToString(Response);
byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString);
response.ContentLength64 = buffer.Length;
System.IO.Stream output = response.OutputStream;
output.Write(buffer, 0, buffer.Length);
output.Close();
}
catch (Exception ex)
{
using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\LogFile.txt"))
{
file.WriteLine(Convert.ToString(ex));
}
public class InsertDataController : ApiController
{
// POST: api/InsertData
public string Post(HttpContent httpContent)
{
var readAsStringAsync = httpContent.ReadAsStringAsync();
var SqlData = readAsStringAsync.Result;
string connectionString = "Server=(local);Database=xxxx;User id=admin;password=1234;";
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
using (SqlCommand ReceiveData = new SqlCommand(SqlData, connection))
ReceiveData.ExecuteNonQuery();
}
return "OK";
}