Relationship between SVC files and WCF projects?

后端 未结 3 1364
梦毁少年i
梦毁少年i 2021-02-01 15:47

When creating a WCF project, the default member files are just ordinary csharp class files, rather than svc files. Are svc files required with a WCF project? When should they be

3条回答
  •  时光说笑
    2021-02-01 16:36

    It is possible to create a WCF project and host it in IIS without using a .svc file.

    Instead of implementing your DataContract in your svc code-behind, you implement it in a normal .cs file (i.e. no code behind.)

    So, you would have a MyService.cs like this:

    public class MyService: IMyService //IMyService defines the contract
    {
        [WebGet(UriTemplate = "resource/{externalResourceId}")]
        public Resource GetResource(string externalResourceId)
        {
            int resourceId = 0;
            if (!Int32.TryParse(externalResourceId, out resourceId) || externalResourceId == 0) // No ID or 0 provided
            {
                WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.NotFound;
                return null;
            }
            var resource = GetResource(resourceId);
            return resource;
        }
    }
    

    Then comes the thing making this possible. Now you need to create a Global.asax with code-behind where you add an Application_Start event hook:

     public class Global : HttpApplication
    {
        void Application_Start(object sender, EventArgs e)
        {
            RegisterRoutes();
        }
    
        private void RegisterRoutes()
        {
            // Edit the base address of MyService by replacing the "MyService" string below
            RouteTable.Routes.Add(new ServiceRoute("MyService", new WebServiceHostFactory(), typeof(MyService)));
        }
    }
    

    One nice thing about this is that you don't have to handle the .svc in your resource URLs. One not so nice thing is that you now have a Global.asax file.

提交回复
热议问题