【问题标题】:Calling WCF Data Service custom method调用 WCF 数据服务自定义方法
【发布时间】:2013-06-03 16:26:03
【问题描述】:

我做了以下自定义方法

[WebGet]
public string GetAllCars()
{

    return "hello";

}

我正在从浏览器中使用此功能,它工作正常 但是当我通过服务引用执行方法通过网络应用程序消费时 它运行良好但通过快速观看无法看到结果,查询操作响应在那里但不知道如何从结果中获取字符串

代码如下:

ServiceReference1.SampleDBEntities uricontext = new ServiceReference1.SampleDBEntities(new Uri("http://localhost/website2/wcfservice1.svc"));
    uricontext.Credentials = System.Net.CredentialCache.DefaultCredentials;
    var proxycontext = uricontext.Execute<String>(new Uri("http://localhost/website2/wcfdataservice1.svc/GetAllCars"));

【问题讨论】:

    标签: wcf-data-services


    【解决方案1】:

    为了得到结果“Strings”,我们需要像这样“foreach”结果变量:

     ServiceReference1.SampleDBEntities uricontext = new ServiceReference1.SampleDBEntities(new Uri("http://localhost/website2/wcfservice1.svc"));
            uricontext.Credentials = System.Net.CredentialCache.DefaultCredentials;
            var proxycontext = uricontext.Execute<String>(new Uri("http://localhost/website2/wcfdataservice1.svc/GetAllCars"));
          //  var s = proxycontext.ToString();
            foreach (var r in proxycontext)
            {
                Response.Write(r.ToString());
            } 
    

    成功了!现在问题已经解决了。

    【讨论】:

    • 我更喜欢使用FirstOrDefault(),执行返回一个IEnumerable&lt;string&gt;,但列表中有0个或1个项目。
    【解决方案2】:

    要从 WCF 数据服务代理获取标量值,最好在结果上调用 FirstOrDefault()

        private T ExecuteScalar<T>(Uri uri)
        {
            return Execute<T>(uri).FirstOrDefault();
        }
    

    用法:

    public string GetAllCars()
    {
        return ExecuteScalar<string>(
            "http://localhost/website2/wcfdataservice1.svc/GetAllCars");
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多