开发者

.NET Web Service - How to make properties invisible

开发者 https://www.devze.com 2023-04-11 16:35 出处:网络
I have an ASP.NET (.asmx) Web Service project that has a method like: public int GetData(Data d); And Data class has properties:

I have an ASP.NET (.asmx) Web Service project that has a method like:

 public int GetData(Data d);

And Data class has properties:

  public class Data
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }

I want the "Id" property to be seen by client, but 开发者_如何转开发not the "Name" property. They all have to be public because inner logic of the application need these properties public.

So how can I set the "Name" property invisible to the client without changing its public accesser, and without making private get, private set?


You can prevent serialisation with the XmlIgnore tag, the proxy classes generated by the client won't contain the property Name.

public class Data
{
  public int Id{get;set;}

  [XmlIgnore()]
  public string Name{get;set;}
}


I believe you are discovering a great reason to use DTOs. A DTO (data transfer object) is what you want to show the outside world.

So in your example your Data object is your domain object, which you use inside of your application, but it contains properties you don't want to give to anyone else. You then have your DataDto object, which is the externally exposed object that you share with other people.

You would then map from Data to DataDto before you send the information out and if necessary, you would map the other way if you received a DataDto in a request. (Or use a tool like AutoMapper).

public class Data
{
    public int Id { get; set; }
    public string Name { get; set; }
}

public class DataDto
{
    public int Id { get; set; }
}


If you can use WCF, when at least one property/member is marked with [DataMember] attribute then all marked are serialized and all othe are not


Use the internal access modifier as this limits access only to items within the same assembly.

public class Data
{
  public int Id{get;set;}
  internal string Name{get;set;}
}


public class Data { public int Id { get; set; } public string Name { get; private set; } }

I've never done this...but this could work? (after @ChrisBD answer)

public class Data
{
  public int Id { get; set; }
  public string Name { get; internal set; }
}


You can also use,

[IgnoreDataMember]
public string Name
{
    get;
    set;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号