views:

548

answers:

2

Is there a way when creating web services to specify the types to use? Specifically, I want to be able to use the same type on both the client and server to reduce duplication of code.

Over simplified example:

    public class Name
    {
        public string FirstName {get; set;}
        public string Surname { get; set; }

        public override string ToString()
        {
            return string.Concat(FirstName, " ", Surname);
        }
    }

I don't want to have recode pieces of functionality in my class. The other thing is that any code that exists that manipulates this class won't work client side as the client side class that is generated would be a different type.

A: 

If you want to have a type or structure shared between your web service and your client, add a public struct to your web service project like so:

public struct Whatever
{
    public string A;
    public int B;
}

then add a method to your web service that has this struct as its return type:

[WebMethod]
public Whatever GiveMeWhatever()
{
    Whatever what = new Whatever();
    what.A = "A";
    what.B = 42;
    return what;
}

After you update your client's web reference, you'll be able to create structs of type Whatever in your client application like so:

Webreference.Whatever what = new Webreference.Whatever();
what.A = "that works?";
what.B = -1; // FILENOTFOUND

This technique lets you maintain the definition of any structures you need to pass back and forth in one place (the web service project).

MusiGenesis
+2  A: 

Okay, I see know that this has been an explicit design decision on the part of SOAP so you're not actually supposed to this. I found the following page that explains why:

Services share schema and contract, not class. Services interact solely on their expression of structures through schemas and behaviors through contracts. The service's contract describes the structure of messages and ordering constraints over messages. The formality of the expression allows machine verification of incoming messages. Machine verification of incoming messages allows you to protect the service's integrity. Contracts and schemas must remain stable over time, so building them flexibly is important.

Having said that there are two other possibilities:

  1. Generate the the web references in Visual Studio or using wsdl.exe. Then go into the generated Reference.cs (or .vb) file and delete the type explicitly. Then redirect to the type that you want that is located in another assembly.
  2. You can share types between web services on the client side by wsdl.exe and the /sharetypes parameter.
Richard Nienaber