Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does adding Name and Namespace to DataContract do?

Tags:

c#

wcf

I tried calling a WebInvoke method called Register which returns takes in a User object and immediately just returns that object. It looks like the following:

User Register(User user)
{
    return user;
}

I am not sure what the Name and Namespace attributes do to the DataContract attribute when calling http://localhost:8081/user/register for example?

The reason I ask is because I initially had my class decorated with the DataContract attribute like this:

[DataContract]
public class User
{
   // Properties
}

When I opened up Fiddler, and sent a Post request, it said method not allowed, but when I changed DataContract to:

[DataContract(Name="User", Namespace="")]

It worked.

like image 406
Xaisoft Avatar asked Sep 27 '10 20:09

Xaisoft


1 Answers

In additional to the other answers, the Namespace in a DataContract allows for two objects of the same name in different namespaces - i.e. versioning.

These two objects are allowed to exist as different properties in a WSDL and will be known deserializable types provided they have different namespaces:

[DataContract(Namespace = "http://myservice/v1/thing")]
V1.Thing

[DataContract(Namespace = "http://myservice/v2/thing")]
V2.Thing

Of course, they need to exist in your C# code as well for it to be valid. Or, alternatively you can change the name that the objects are known by using the Name attribute for clarity.

[DataContract(Name = "Thing")]
V1.Thing

[DataContract(Name= = "newThing")]
V2.Thing

You might use this when the class' name has changed in your project, but you need to support existing clients that use the 'old' names.

In summary, the Name and Namespace properties control how your objects will be serialized and deserialized when transmitted over the wire. When you set them, you are controlling how the client will see your data contract.

like image 152
Kirk Broadhurst Avatar answered Sep 18 '22 12:09

Kirk Broadhurst