【问题标题】:Relationship between SVC files and WCF projects?SVC 文件和 WCF 项目之间的关系?
【发布时间】:2010-01-21 22:31:25
【问题描述】:

在创建 WCF 项目时,默认的成员文件只是普通的 csharp 类文件,而不是 svc 文件。 WCF 项目是否需要 svc 文件?什么时候应该使用它们?

【问题讨论】:

    标签: c# wcf iis


    【解决方案1】:

    .svc 文件在 IIS 中托管 WCF 服务时使用。

    请参阅 Microsoft 的文档 herehere

    IIS 中有一个模块可以处理 .svc 文件。实际上,它是 ASPNET ISAPI 模块,它将对 .svc 文件的请求移交给已为 ASPNET 配置的处理程序工厂类型之一,在这种情况下

    System.ServiceModel.Activation.HttpHandler, System.ServiceModel, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089


    如果您在 IIS 以外的地方托管 WCF 服务,则不需要 .svc 文件。

    【讨论】:

    【解决方案2】:

    如果您使用的是 .net 4.0 或更高版本,您现在可以通过以下配置“模拟”.svc:

    <system.serviceModel>
       <!-- bindings, endpoints, behaviors -->
       <serviceHostingEnvironment >
          <serviceActivations>
             <add relativeAddress="MyService.svc" service="MyAssembly.MyService"/>
          </serviceActivations>
       </serviceHostingEnvironment>
    </system.serviceModel>
    

    那么您不需要物理 .svc 文件或 global.asax

    【讨论】:

    • 这件事中的.svc 和 global.asax 文件是否可以被视为“已弃用”?
    【解决方案3】:

    可以在不使用 .svc 文件的情况下创建 WCF 项目并将其托管在 IIS 中。

    您无需在 svc 代码隐藏中实现 DataContract,而是在普通的 .cs 文件中实现它(即没有代码隐藏。)

    因此,您将拥有这样的 MyService.cs:

    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;
        }
    }
    

    然后是使这成为可能的事情。现在您需要创建一个带有代码隐藏的 Global.asax,您可以在其中添加一个 Application_Start 事件挂钩:

     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)));
        }
    }
    

    这样做的好处是您不必处理资源 URL 中的 .svc。一件不太好的事情是你现在有一个 Global.asax 文件。

    【讨论】:

      猜你喜欢
      • 2012-03-24
      • 2016-09-16
      • 2018-08-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-01
      • 1970-01-01
      相关资源
      最近更新 更多