System.IO.Stream to Data Transfer Object prior to

2019-03-04 15:35发布

This question builds upon an earlier question (although off-topic) I asked yesterday. Please give it a read first.

OK - in my WCF REST project, I have been converting my domain objects to data transfer objects (DTOs) prior to JSON serialization to mobile clients. For example, here is my User DTO:

[DataContract]
public class UserDto
{
    [DataMember]
    public string UserId { get; set; }

    [DataMember]
    public string UserName { get; set; }

    [DataMember]
    public string Email { get; set; }

    [DataMember]
    public string Password { get; set; }

}

And in my User.svc service, the UserDto gets serialized back to the client as such:

 public UserDto GetUserById(string userid)
        {
            var obj = UserRepository.GetUserById(userid);
            return new Contracts.UserDto
            {
                Email = obj.Email.ToString(),
                Password = obj.Password.ToString(),
                UserId = obj.UserId.ToString(),
                UserName = obj.UserName.ToString()
            };
        }

Now, I have a base class that exposes the following method:

public virtual Stream GetGroupById(string id)

to my Dashboard.svc service. It returns the following:

return new MemoryStream(bytes);

In this service, I want to override the method and return the results to the client in the same way that I am serializing my above UserDto.

MY QUESTION IS - how do you convert a method of type Stream into a Data transfer object and serialize the results (as a JSON-formatted string) to the client???

Thanks for your help.

1条回答
趁早两清
2楼-- · 2019-03-04 16:19

I might be mis-understanding things here, but what you're trying to do is backwards. You would first get your domain object, then convert to the DTO, then write the serialized DTO to the stream:

public virtual Stream GetGroupById(string id)
{
    var user = UserRepository.GetUserById(id);
    var dto = new Contracts.UserDto
              {
                  Email = user.Email.ToString(),
                  Password = user.Password.ToString(),
                  UserId = user.UserId.ToString(),
                  UserName = user.UserName.ToString()
              }

    var serializer = new JavaScriptSerializer()l
    var bytes = Encoding.UTF8.GetBytes(serializer.Serialize(dto));

    return new MemoryStream(bytes);
}

The Stream being returned to the client will contain the JSON for the serialized DTO.

查看更多
登录 后发表回答