c#写入当前的http响应

时间:2016-03-07 13:47:40

标签: c# wcf http

我是c#中wcf的新手,我似乎找不到解决方案,我认为这是一个非常简单的问题。我想要做的就是在我所做的请求处理程序中写入响应的响应主体。如果有办法做出回应并发送它也可以起作用。这是代码......

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

    }

当前代码设置响应状态代码和描述,但我真的需要能够写入响应正文或能够做出具有正文的响应并被发送回我的客户端。提前谢谢。

1 个答案:

答案 0 :(得分:0)

您正在使用[OperationContract],因此您应该让合同​​返回一个对象(而不是无效)并在实现中返回它。如果要返回一个类,则应使用[DataContract]属性对其进行注释...

检查此答案 - &gt; WCF service: Returning custom objects