2013-08-02 3 views
3

Я разрабатывает WCF Rest Service и у меня есть это на мой ServiceContract:Используя тот же метод PUT и POST

[OperationContract] 
    [WebInvoke(Method = "POST", 
     UriTemplate = "/users", 
     RequestFormat = WebMessageFormat.Json, 
     ResponseFormat = WebMessageFormat.Json, 
     BodyStyle = WebMessageBodyStyle.Bare)] 
    User AddOrUpdateUser(User user); 

    [OperationContract] 
    [WebInvoke(Method = "PUT", 
     UriTemplate = "/users", 
     RequestFormat = WebMessageFormat.Json, 
     ResponseFormat = WebMessageFormat.Json, 
     BodyStyle = WebMessageBodyStyle.Bare)] 
    User AddOrUpdateUser(User user); 

Я собираюсь использовать User AddOrUpdateUser(User user); для POST и PUT:

public User AddOrUpdateUser(User user) 
    { 
     if (user == null) 
      throw new ArgumentNullException("user", "AddOrUpdateUser: user is null"); 

     using (var context = new AdnLineContext()) 
     { 
      context.Entry(user).State = user.UserId == 0 ? 
             EntityState.Added : 
             EntityState.Modified; 
      context.SaveChanges(); 
     } 

     return user; 
    } 

Я следую за этим pattern, чтобы сделать это.

Но, я получаю сообщение об ошибке:

The type 'MyCompanyWCFService.IMyCompanyService' already contains a definition for 
'AddOrUpdateUser' with the same parameters 

Как я могу исправить эту проблему?

+1

Это может быть удвоена со следующим post, посмотрите, поможет ли это: http://stackoverflow.com/questions/555073/enable-multiple-http-methods-on-a-single-operation – cocogorilla

+0

Вы пытались поместить оба атрибута «WebInvoke» в один и тот же метод? – Jay

ответ

1

У вас не может быть два метода с одной и той же сигнатурой - это проблема C#, а не WCF. У вас есть в основном два варианта, чтобы пойти сюда. Во-первых, есть два различных способа, и имеют один вызов другой, или есть третий метод, названный обоими):

public interface ITest 
{ 
    [OperationContract] 
    [WebInvoke(Method = "POST", 
     UriTemplate = "/users", 
     RequestFormat = WebMessageFormat.Json, 
     ResponseFormat = WebMessageFormat.Json, 
     BodyStyle = WebMessageBodyStyle.Bare)] 
    User AddUser(User user); 

    [OperationContract] 
    [WebInvoke(Method = "PUT", 
     UriTemplate = "/users", 
     RequestFormat = WebMessageFormat.Json, 
     ResponseFormat = WebMessageFormat.Json, 
     BodyStyle = WebMessageBodyStyle.Bare)] 
    User UpdateUser(User user); 
} 

а реализация:

public class Service 
{ 
    public User AddUser(User user) { return AddOrUpdateUser(user); } 
    public User UpdateUser(User user) { return AddOrUpdateUser(user); } 
    private User AddOrUpdateUser(User user) 
    { 
     if (user == null) 
      throw new ArgumentNullException("user", "AddOrUpdateUser: user is null"); 

     using (var context = new AdnLineContext()) 
     { 
      context.Entry(user).State = user.UserId == 0 ? 
             EntityState.Added : 
             EntityState.Modified; 
      context.SaveChanges(); 
     } 

     return user; 
    } 
} 

Другой альтернативой было бы иметь один единственный метод, который принимает несколько HTTP-методов; вы можете это сделать, указав Method = "*" на атрибут WebInvoke. Но если идти по этому пути, вы должны подтвердить в пределах операции, что входящий глагол HTTP является одним из тех, кого вы ожидаете:

public interface ITest 
{ 
    [OperationContract] 
    [WebInvoke(Method = "*", 
     UriTemplate = "/users", 
     RequestFormat = WebMessageFormat.Json, 
     ResponseFormat = WebMessageFormat.Json, 
     BodyStyle = WebMessageBodyStyle.Bare)] 
    User AddOrUpdateUser(User user); 
} 

И реализация:

public class Service 
{ 
    public User AddOrUpdateUser(User user) 
    { 
     var method = WebOperationContext.Current.IncomingRequest.Method.ToUpperInvariant(); 
     if (method != "POST" || method != "PUT") 
     { 
      throw new WebFaultException(HttpStatusCode.MethodNotAllowed); 
     } 

     if (user == null) 
      throw new ArgumentNullException("user", "AddOrUpdateUser: user is null"); 

     using (var context = new AdnLineContext()) 
     { 
      context.Entry(user).State = user.UserId == 0 ? 
             EntityState.Added : 
             EntityState.Modified; 
      context.SaveChanges(); 
     } 

     return user; 
    } 
} 
Смежные вопросы