这是我第一次在博客写作,主要是为了记录一下自己在工作或者生活中的一些所得,希望能够用作一个备忘录吧。
首先,在VS上面建立一个项目,不用特定的建立wcf项目,直接建立一个空项目即可,废话不多说直接上代码。
这个是服务端的入口程序,因为服务比较简单,不需要手动配置,直接用代码的方式添加配置。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.Configuration;
using System.ServiceModel.Description;
namespace OrderMenu.Wcf
{
public class Program
{
static void Main(string [] args)
{
try
{
Uri baseAddress=new Uri("http://localhost:8001/Service");
using(ServiceHost host = new ServiceHost(typeof(Service1), baseAddress))
{
WebHttpBinding binding = new WebHttpBinding();
ServiceEndpoint endpoint = host.AddServiceEndpoint(typeof(IService1),binding,baseAddress);
WebHttpBehavior behavior = new WebHttpBehavior();
endpoint.Behaviors.Add(behavior);
host.Opened += delegate
{
Console.WriteLine("服务启动");
};
host.Open();
Console.ReadLine();
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
}
}
其中Service1和IService1是服务和接口,因此还要完成这两个类的编写.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.ServiceModel.Web;
using System.IO;
namespace OrderMenu.Wcf
{
[ServiceContract]
public interface IService1
{
[OperationContract]
[WebGet(
UriTemplate = "GetTest/{username}",
ResponseFormat = WebMessageFormat.Json,
RequestFormat = WebMessageFormat.Json)]
string GetTest(string username);
<pre name="code" class="csharp">using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.IO;
namespace OrderMenu.Wcf
{
// 注意: 使用“重构”菜单上的“重命名”命令,可以同时更改代码和配置文件中的类名“Service1”。
public class Service1 : IService1
{
public string GetTest(string username)
{
return "你好" + username;
}
}
}
将相关的dll引进去了之后接下来就可以运行了。此处的app.config是不需要配置的。
效果大致如下: