我正在使用Visual Basic .NET编写程序,以在本地networking上的PC上执行操作。
我正在寻找一些非常简单的解决scheme,让我:
例如:inputhttp://192.168.1.72/function/argument1/argument2
会运行我的winforms应用程序在本地联网的机器上的“function”子/function,并通过参数1和参数2(如果它们被包括在内) ,然后返回响应页面/string作为反馈请求的浏览器
任何人都可以用这种方式指出我的意思吗? 我正在寻找相当简单的东西,但是可靠的,因为它可能会昼夜不停地运行
我正在寻找相当简单的东西,但是可靠的,因为它可能会昼夜不停地运行
我认为最简单的方法是使用WCF的WebServiceHost类:
[ServiceContract] public class MyService { [OperationContract, WebGet(UriTemplate = "/function/{argument1}/{argument2}")] public string AMethod(string argument1, string argument2) { return argument1 + " " + argument2; } }
把这一行放到你的应用程序的formload(或其他任何入口点)
var wsh = new WebServiceHost(typeof(MyService), new Uri("http://0.0.0.0/MyService")); wsh.Open();
并从浏览器中调用http://192.168.1.72/Myservice/function/a/b
。 就这些。
—-全职代码—-
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.ServiceModel; using System.ServiceModel.Web; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } protected override void OnLoad(EventArgs e) { var wsh = new WebServiceHost(typeof(MyService), new Uri("http://0.0.0.0/MyService")); wsh.Open(); } } [ServiceContract] public class MyService { [OperationContract, WebGet(UriTemplate = "/function/{argument1}/{argument2}")] public string AMethod(string argument1, string argument2) { return argument1 + " " + argument2; } ///******** EDIT ******** /// [OperationContract, WebGet(UriTemplate = "/function2/{argument1}/{argument2}")] public Stream F2(string argument1, string argument2) { return ToHtml("<html><h1>" + argument1 + " " + argument2 + "</h1></HtmlDocument>"); } static Stream ToHtml(string result) { var data = Encoding.UTF8.GetBytes(result); WebOperationContext.Current.OutgoingResponse.ContentType = "text/html; charset=utf-8"; WebOperationContext.Current.OutgoingResponse.ContentLength = data.Length; return new MemoryStream(data); } ///END OF EDIT } }
是否有可能确定请求来自的IP地址?
var m = OperationContext.Current .IncomingMessageProperties[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty; var address = m.Address;
任何方式使{参数}可选?
从WebGet
属性中删除UriTemplate
参数。 那么你的网址将是
http://1192.168.1.72/MyService/AMethod?argument1=aaaa&argument2=bbb
如果你想使参数2为可选,调用为
http://1192.168.1.72/MyService/AMethod?argument1=aaaa
和argument2将获得您的方法的默认值。
你所需要的只是某种形式的网络服务。 您可能想要使用ASP.NET Web API使用REST Web服务。
单独的进程间通信机制将不是必需的。