如何从Web服务返回自定义类? [英] How can I return a custom class from a web service?

查看:131
本文介绍了如何从Web服务返回自定义类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个网络服务返回自定义类(用户)的对象:

I have a web service that returns an object of a custom class (user):

Web服务代码

public class User
{
    public string login { get; set; }
    public string firstName { get; set; }
    public string lastName { get; set; }
    public string email { get; set; }

}

[WebMethod]
public User GetUserInfo(int userID)
{
    ITDashboardDataContext db = new ITDashboardDataContext();

    User usr = (from u in db.tl_sb_users
                where u.userID == userID
                select new User
                {
                    firstName = u.firstName,
                    lastName = u.lastName,
                    email = GetUserEmail(userID),
                    login = u.login

                }).FirstOrDefault();

    return usr;
}

我想在调用Web服务时将结果作为用户对象(我已经在此应用中重新定义了用户类):

I want to cast the result as a user object when I call the web service from another application (I've redefined the user class in this app, too):

调用应用代码

public class User
{
    public string login { get; set; }
    public string firstName { get; set; }
    public string lastName { get; set; }
    public string email { get; set; }
}



我试图带回一个用户对象: p>

I'm trying to bring back a user object with this:

RolloutWriter.RolloutWriter rw = new RolloutWriter.RolloutWriter();
rw.Credentials = new NetworkCredential("myuser", "mypassword", "mydomain");

var vu = rw.GetUserInfo(userID);

User u = (from v in vu
         select new User {
             email = vu.email,
             firstName = vu.firstName,
             lastName = vu.lastName,
             login = vu.login
         }).FirstOrDefault();

这不工作 - 它告诉我:

this doesn't work - it tells me:

Could not find an implementation of the query pattern for source type 'amstaffsite.RolloutWriter.User'.  'Select' not found.

如何获取用户对象?

推荐答案

当你添加一个对webservice的引用,.net读入wsdl&

When you add a reference to a webservice, .net reads in the wsdl & creates all the types it needs to use that service.

你得到的是 user生成的类型。它具有与服务器使用的类型完全相同的签名,但它不会是相同的类型 - 这就是为什么你得到类型转换异常。您需要在原始类型上创建工厂或构造函数,才能将生成的用户转换为原始用户类型。

What you're getting back is the generated type for user. It has exactly the same signature as the type used by the server, but it won't be the same type - that's why you get the type conversion exception. You'll need to create either a factory, or a constructor on your original type, to convert from the generated user to the original user type.

如果您使用wcf ,你可以把类型放入一个共同的程序集,由客户端和客户端共享。服务器。 WCF可以知道这些类型是等效的&重新使用它们,而不是重新生成类型。

If you were using wcf, you could put the types into a common assembly, shared by both client & server. WCF can figure out that these types are equivalent & re-use them, rather then regenerating the types.

这篇关于如何从Web服务返回自定义类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆