小型桌面应用程序如何与ASP.NET网页进行通信?

时间:2012-08-22 12:11:59

标签: c# asp.net winforms

我已经构建了一个小型Windows应用程序,可以找到计算机的MAC地址。我还有一个ASP.NET网页。当我的登录页面加载时,我正在运行该可执行文件。

我正在尝试获取MAC地址值。我怎样才能做到这一点?

我的桌面应用程序可以将该值返回到我的网页吗?

这是我到目前为止所尝试的内容。

桌面应用程序代码:

public string GetSystemMACID()
{
    string systemName = System.Windows.Forms.SystemInformation.ComputerName;
    try
    {
        ManagementScope theScope = new ManagementScope("\\\\" + Environment.MachineName + "\\root\\cimv2");
        ObjectQuery theQuery = new ObjectQuery("SELECT * FROM Win32_NetworkAdapter");
        ManagementObjectSearcher theSearcher = new ManagementObjectSearcher(theScope, theQuery);
        ManagementObjectCollection theCollectionOfResults = theSearcher.Get();

        foreach (ManagementObject theCurrentObject in theCollectionOfResults)
        {
            if (theCurrentObject["MACAddress"] != null)
            {
                 string macAdd = theCurrentObject["MACAddress"].ToString();
                 return macAdd.Replace(':', '-');
            }
        }
    }
    catch (ManagementException e)
    {
    }
    catch (System.UnauthorizedAccessException e)
    {

    }
    return string.Empty;
}

返回值仅分配给Label

有人可以建议我是否有可能?欢迎任何建议。

1 个答案:

答案 0 :(得分:2)

您可以将站点设置为接受名为MACAddress的查询参数。让桌面应用程序POST到网站;张贴cookie的值。这可能会有所帮助:

using System.Net;

...

var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.UseDefaultCredentials = true;
httpWebRequest.ContentType = "application/x-www-form-urlencoded";
httpWebRequest.Method = "POST";

byte[] requestBytes = Encoding.UTF8.GetBytes(queryString);
httpWebRequest.ContentLength = requestBytes.Length;

using (var requestStream = httpWebRequest.GetRequestStream())
{
    requestStream.Write(requestBytes, 0, requestBytes.Length);
    requestStream.Close();
}

查询字符串看起来像

"MACAddress=" + macAdd 

-------------根据要求更新---------------

在桌面应用程序中,添加using语句。您可能还需要在解决方案资源管理器中添加对Dll的引用。

然后,按如下方式创建一个名为PostMacAddress的方法:

public void PostMacAddress(string url, string macAdd)
{
   var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
   httpWebRequest.UseDefaultCredentials = true;
   httpWebRequest.ContentType = "application/x-www-form-urlencoded";
   httpWebRequest.Method = "POST";

   var queryString = "MACAddress=" + macAdd; 

   byte[] requestBytes = Encoding.UTF8.GetBytes(queryString);
   httpWebRequest.ContentLength = requestBytes.Length;

   using (var requestStream = httpWebRequest.GetRequestStream())
   {
      requestStream.Write(requestBytes, 0, requestBytes.Length);
      requestStream.Close();
   }
}

我不确定你不理解的是什么(不是试图表达意思)。我在这里简化了,但是,POSTing是一种用于向网站发送数据的HTTP协议。另一个是GET(读取数据的协议)。

希望有所帮助!

-------更新以显示网络方面......-----------

在Page_Load方法中,您需要获取如下所示的QueryString:

protected void Page_Load(object sender, EventArgs e)
{
     if (!String.IsNullOrEmpty(Request.QueryString["MACAddress"])
         lblMacAddress.Text = Request.QueryString["MACAddress"];
}