WCF自定义地址路由映射(不用svc文件)

一般在创建WCF服务时会用Serivce.svc文件访问,地址如:http://localhost/applicationname/Serivce.svc/Name

现在用路由映射成:http://localhost/applicationname/MyService/Name  方法如下:

首先在Global.asax中的Application_Start事件中添加以下代码:

void Application_Start(object sender, EventArgs e)
    {
        System.Web.Routing.RouteTable.Routes.Add(newSystem.ServiceModel.Activation.ServiceRoute("MyService", new System.ServiceModel.Activation.WebServiceHostFactory(), typeof(Service))); 
    }

其中"MyService"为自定义要在地址栏中映射的名称,如: http://localhost/applicationname/MyService/Name

typeof(Service)中的"Service"为WCF中服务实现类Service.cs,一般继承IService.cs接口

接下来必须在web.config中<serviceHostingEnvironmentmultipleSiteBindingsEnabled="true" aspNetCompatibilityEnabled="true">的aspNetCompatibilityEnabled设为true

然后再在Service.cs服务类上面添加:

[AspNetCompatibilityRequirements(RequirementsMode=AspNetCompatibilityRequirementsMode.Allowed)]  //记得引用using System.ServiceModel.Activation;

public class Service : IService
{

public string GetName(string Name)

     {

return "your name is " + Name;

     }

}

此外还有IService.cs接口中方法声明中设置UriTemplate以接受参数:

[ServiceContract]
public interface IService
{

        [OperationContract, WebGet(UriTemplate = "{Name}", BodyStyle =WebMessageBodyStyle.Bare, ResponseFormat = WebMessageFormat.Xml)]
string GetName(string Name);

}

转载于:https://www.cnblogs.com/zisezhixin/p/3891342.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值