1 添加服务类 WebServiceHost
using System.ServiceModel; using System.ServiceModel.Web; using System.Web.Services.Protocols;
[ServiceContract(Namespace = "http://www.123.com")] [ServiceBehavior(Namespace = "http://www.123.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(); } } }