wcf的简单服务建立

这是我第一次在博客写作,主要是为了记录一下自己在工作或者生活中的一些所得,希望能够用作一个备忘录吧。

首先,在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是不需要配置的。 

效果大致如下:


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值