Вопрос

Hi I have been reading some lecture notes and I cant work out why this method:

[OperationContract]
Student PostStudent (Student student);

Is good.

And this method is bad:

[OperationContract]
void PostStudent (string firstname, string lastname etc..);

Yet my implemented version is this:

[OperationContract]
void PostStudent(Student student);

So Im not sure if my implemented version is bad, Im also unsure how my lecturer got

Student PostStudent (Student student); // ?

Это было полезно?

Решение

Web services are built upon the use of messages. A message in WCF is defined by writing a class, which your Student class is, and (optionally) marking it with the DataContract attribute. This enables versioning and setting various properties on the properties of that class (although the latter effect can also be achieved using the MessageParameter attribute).

So yes, PostStudent (string firstname, string lastname etc..) is bad.

Whether or not to return something from that method is up to you. A void can be perfectly fine, because using for example SOAP you can return a Fault indicating why the user could not be created: no error means the creation went well.

When you want to inpect the created Student, you might as well define a PostStudentResult (or a PostResult<T>) class and return that, containing the properties Student (or T Result) and Status, where the first contains the student as it's created and the latter indicates whether or not the creation was successful.

Другие советы

Return values in Web services are not bad practice in general. So it is about the parameters. Data that belongs together should be wrapped in in Objects.

Further a Post method should not get an return value at all. You post it and in case of an error your will receive an Exception.

If your need to receive some student you should create an method like:

Student GetStudentByName(string name);

If it is a WCF then specifying Action can also be a good practice with Void methods.

Like evryone else said, having too many method parameters is bad practice. Any way I can see only one difference between your signature and the good signature you mentioned. Having the student object as return will give you the ability of having the Id of the student after addition in db for example. Same thing applies for any other calculated properties of the object. Have a void method will force you to load the object again which means an extra trip to server in case you wanted to use the object directly after posting it. Any way having void WCF method is not bad if returning the object is nothing but an extra bandwith.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top