我有一个简单的WCF数据服务服务,我想公开一个服务操作,如下所示:
[System.ServiceModel.ServiceBehavior(IncludeExceptionDetailInFaults = true)]
public class ProductDataService : DataService<ProductRepository>
{
// This method is called only once to initialize service-wide policies.
public static void InitializeService(IDataServiceConfiguration config)
{
config.SetEntitySetAccessRule("*",
EntitySetRights.ReadMultiple | EntitySetRights.ReadSingle);
config.SetServiceOperationAccessRule("*",
ServiceOperationRights.All);
config.UseVerboseErrors = true;
}
// This operation isn't getting generated client side
[WebGet]
public IQueryable<Product> GetProducts()
{
// Simple example for testing
return (new ProductRepository()).Product;
}
为什么在客户端添加服务引用时GetProducts
方法不可见?
我正在运行Visual Studio 2008 SP1和.NET Framework 3.5 SP1。我还下载并安装了此更新:
答案 0 :(得分:10)
终于解决了这个问题。要在数据服务类上调用服务操作,您需要使用数据服务上下文对象的CreateQuery
或Execute
方法。例如:
ProductDataService ctx = new ProductDataService(
new Uri("http://localhost:1234/ProductDataService.svc/"));
// Method 1:
DataServiceQuery<Product> q = ctx.CreateQuery<Product>("GetProducts");
List<Product> products = q.Execute().ToList();
// Method 2:
Uri uri = new Uri(String.Format("{0}GetProducts", ctx.BaseUri),
UriKind.RelativeOrAbsolute);
List<Product> products = ctx.Execute<Product>(uri).ToList();
如果需要参数,请说明具有此签名的服务操作的产品类别:
[WebGet]
public IQueryable<Product> GetProducts(string category)
我们会这样做:
// Method 1:
DataServiceQuery<Product> q = ctx.CreateQuery<Product>("GetProducts")
.AddQueryOption("category", "Boats") ;
List<Product> products = q.Execute().ToList();
// Method 2:
Uri uri = new Uri(String.Format("{0}GetProducts?category={1}",
ctx.BaseUri, "Boats"), UriKind.RelativeOrAbsolute);
List<Product> products = ctx.Execute<Product>(uri).ToList();
答案 1 :(得分:1)
(这个答案是不正确(见评论),但故意留在这里以阻止其他答案盲目地陷入同一个洞)
[OperationContract]
[OperationContract, WebGet]
public IQueryable<Product> GetProducts()
{
// Simple example for testing
return (new ProductRepository()).Product;
}
(理想情况下,服务本身就是[ServiceContract]
)
答案 2 :(得分:0)
我在以下示例中遇到了类似的问题
[System.ServiceModel.ServiceBehavior(IncludeExceptionDetailInFaults = true)]
public class TestService : DataService<MyService>
{
// This method is called only once to initialize service-wide policies.
public static void InitializeService(DataServiceConfiguration config)
{
config.SetEntitySetAccessRule("*", EntitySetRights.AllRead);
config.SetServiceOperationAccessRule("*", ServiceOperationRights.AllRead);
config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V2;
}
[WebGet]
public IQueryable<string> GetStrings(int index)
{
string[] list = { "One", "two" };
return list.AsQueryable();
}
}
当我浏览服务http://localhost:3059/TestService.svc
时,列表没有列出具有WebGet属性的方法,但我能够使用
http://localhost:3059/TestService.svc/GetStrings?index=1
这告诉我,WCF数据服务定义没有列出通过Web浏览器浏览时的操作,或者有一些未记录的方法来获取列表中的操作。