1 新增服務類 WebServiceHost
[ServiceContract(Namespace = "http://www.RePower.com")] [ServiceBehavior(Namespace = "http://www.RePower.com", InstanceContextMode = InstanceContextMode.Single, AddressFilterMode = AddressFilterMode.Any)] [SoapDocumentService(RoutingStyle = SoapServiceRoutingStyle.RequestElement)] public class WebServiceHost: IWebServiceHost { [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json)] public string Get() { return "你好"; } } public interface IWebServiceHost { } }
2 開啟服務
using System; using System.Security.Policy; using System.ServiceModel; using System.ServiceModel.Description; using System.Windows; namespace WpfNetFormAddApi { /// <summary> /// MainWindow.xaml 的互動邏輯 /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } ServiceHost Host; private void Button_Click(object sender, RoutedEventArgs e) { Host = new ServiceHost(typeof(WebServiceHost)); Host.OpenTimeout = TimeSpan.FromMinutes(30); WebHttpBinding httpBinding = new WebHttpBinding(WebHttpSecurityMode.None); httpBinding.MaxReceivedMessageSize = 2147483647; httpBinding.MaxBufferPoolSize = 2147483647; var endPoint = Host.AddServiceEndpoint(typeof(WebServiceHost), httpBinding, "http://localhost:7894/Index.asmx"); WebHttpBehavior webHttpBehavior = new WebHttpBehavior(); endPoint.Behaviors.Add(webHttpBehavior); Host.Open(); } } }