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(new System.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中<serviceHostingEnvironment multipleSiteBindingsEnabled="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/therock/archive/2011/12/04/2275258.html
總結
以上是生活随笔為你收集整理的WCF自定义地址路由映射(不用svc文件)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: c# 中Stopwatch 类的运用
- 下一篇: C++ template 学习归纳2