为什么数据服务不向应用程序返回值,而是将其返回给浏览器?怎么解决?

时间:2012-12-10 05:23:00

标签: c# web-services odata

只需要一个简单的OData网络服务:

public class TestService : DataService<ASUTBEntities>
{
    public static void InitializeService(DataServiceConfiguration config)
    {
        config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V2;
        config.SetEntitySetAccessRule("*", EntitySetRights.AllRead
             | EntitySetRights.WriteMerge
             | EntitySetRights.WriteReplace);
        config.SetServiceOperationAccessRule("*", ServiceOperationRights.All);
        config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V2;
    }

    [WebGet]
    public List<Search_Result1> FindCarOwner(string searchString)
    {
        List<Search_Result1> result = new List<Search_Result1>();
        result.AddRange(CurrentDataSource.FindContragents(searchString).ToList());
        return result;
    }
}

Search_Result1 - 是一种复杂类型,由EDMX文件中的Sql Server存储过程自动生成。 如果我在浏览器中键入如下内容:hxxp://MyWebService/Test.svc/FindCarOwner?searchString ='SomeString'。它返回如下内容:

<FindCarOwner xmlns="http://schemas.microsoft.com/ado/2007/08/dataservices">
    <element xmlns:p2="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata" p2:type="ASUTBModel.Search_Result1">
        <Name>
        Name of the company
        </Name>
        <ID p2:type="Edm.Int32">538175</ID>
    </element>
    ... and 3 elements more (total 4 elements)
</FindCarOwner>

但是如果我尝试从应用程序调用此函数,它将返回List,其容量= 4且Count = 0。我是这样做的:

ASUTBOData.ASUTBEntities context = new ASUTBOData.ASUTBEntities(new Uri(servicePath));
context.Credentials = System.Net.CredentialCache.DefaultCredentials;
context.MergeOption = MergeOption.NoTracking;
List<Search_Result1> preresult;
try
{
    preresult = context.Execute<Search_Result1>(new Uri("hxxp://MyWebService/Test.svc/FindCarOwner?searchString='SomeString'")).ToList();
}
catch (Exception e)
{
    return null;
}

为什么应用程序无法转换收到的值?它是可以修复的,还是我必须找到其他解决方案?

1 个答案:

答案 0 :(得分:0)

数据服务客户端不支持除了Schema中的EntityType实现,在OData中描述(对我而言,它是MyWebService / Test.svc / $ metadata)。 我能找到的唯一解决方案是使用System.Net中的WebClient

WebClient wc = new WebClient();
wc.UseDefaultCredentials = true;

XDocument xdoc = XDocument.Parse(wc.DownloadString(new Uri(request)));
var res = xdoc.Root.Descendants( ((XNamespace)@"http://schemas.microsoft.com/ado/2007/08/dataservices") + 
                                            "element");

preresult = res.Select(xe => xe.Value).ToList();