2016-03-07 43 views
0

我是新来的wcf在c#中,我似乎无法找到解决方案,我觉得是一个非常简单的问题。我想要做的就是在我所做的请求处理程序中写入响应的响应主体。如果有办法做出回应并发送也可以发挥作用。下面是代码...c#写入当前http响应

[WebInvoke(Method = "POST", UriTemplate = "users", BodyStyle = WebMessageBodyStyle.Wrapped, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)] 
    [OperationContract] 
    void addUser(String username, String firstname, String lastname, String email, String hash) 
    { 
     Console.WriteLine(DateTime.Now + " Packet receieved"); 

     //Stores the response object that will be sent back to the android client 
     OutgoingWebResponseContext response = WebOperationContext.Current.OutgoingResponse; 

     String description = "User added"; 
     response.StatusCode = System.Net.HttpStatusCode.OK; 

     //Tries to add the new user 
     try 
     { 
      userTable.Insert(username,firstname,lastname,email,hash); 
     } 
     catch (SqlException e) 
     { 
      //Default response is a conflict 
      response.StatusCode = System.Net.HttpStatusCode.Conflict; 

      description = "Bad Request (" + e.Message + ")"; 

      //Check what the conflict is 
      if (userTable.GetData().AsEnumerable().Any(row => username == row.Field<String>("username"))) 
      { 
       description = "Username in use"; 
      } 
      else if (userTable.GetData().AsEnumerable().Any(row => email == row.Field<String>("email"))) 
      { 
       description = "Email address in use"; 
      } 
      else 
      { 
       response.StatusCode = System.Net.HttpStatusCode.BadRequest; 
      } 
     } 

     //dsiplay and respond with the description 
     Console.WriteLine(description); 
     response.StatusDescription = description; 

    } 

当前的代码设置响应状态代码和说明,但是我真正需要的是能够写入响应机构或能够使具有身体,得到响应发回给我的客户。提前致谢。

回答

0

您正在使用[OperationContract],因此您应该使契约返回一个对象(而不是void),并在实现中返回它。如果你想返回一个类,你应该使用[DataContract]属性注释吧...

检查这个答案 - >WCF service: Returning custom objects

+0

现在看来那么明显。谢谢 – Mitchell

+0

不客气 – Dekay