0

I'm new to wcf in c# and I can't seem to find a solution to what I feel is quite a simple problem. All I want to do is write to the response body of a response in a request handler I've made. If there is a way to make a response and send it that could also work. Here is the code...

    [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;

    }

The current code sets the response status code and description but I really need to be able to write to the response body or be able to make a response that has a body and gets sent back to my client. Thanks in advance.

Mitchell
  • 13
  • 5

1 Answers1

0

You are using [OperationContract] so you should make the contract return an object (instead of being void) and just return it in the implementation. If you want to return a class you should annotate it with the [DataContract] attribute...

Check this answer -> WCF service: Returning custom objects

Community
  • 1
  • 1
Dekay
  • 111
  • 1
  • 2
  • 12