开发者

How to return multiple results from web method?

I develop winforms app. One of my forms accepts user input and calls a web service to add the input into the DB. The input must be unique, however I have no way of knowing if it is unique in the client side. I send the input to the WS and it is responsible of either adding it to the DB or informing the client that the input already exists.

What is the correct way to implement that?

Should I make two calls to the WS, one to know if it is unique and one to insert into the DB? I sense synchronization issues + two round trips across boundary.

Should I return an enum, ValueNotUnique and ValueInserted开发者_StackOverflow社区Successfully?

Or perhaps throw an exception? That sounds not performance wise, plus I don't like using exceptions for things I already know that might not work.

Is there a nice design to this mess? Help appreciated, thanks in advance!


I would probably do something like this:

  • define an enumeration of result values; ValueAlreadyExists, ValueInserted etc.
  • define a return object type that would include
    • the result of the operation, as that enum type
    • if the value already existed - possibly something like an ID or even some of the data
    • if the value was inserted successfully, the new ID

So you'd have:

public enum OpResult
{
   ValueInserted,
   ValueAlreadyExists
}

and a result type:

public class ResponseType
{
    public OpResult Result { get; set; }
    public int UniqueID { get; set; }
}

With this approach, you can easily

  • extend the enumeration and add more possible outcomes for your operation
  • extend the response type and add more information if you need it


Your web method can return a custom class that has multiple properties. Web services are not required to only return primitive or atomic types. Mark the custom class Serializable and ensure that any properties are also serializeable, etc.

Alternatively you can throw an exception if you consider the cases where you didn't insert to be errors and catch the exception in the calling application.


I would do it the following way:

You send the request to the server. There you check if the value is correct. If it is correct you make an insert and send a valid result back to your client. If it is not correct you send an error message back.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜