Http Call的奇怪问题

时间:2015-03-05 10:32:23

标签: c# wcf httpwebrequest http-post

我使用http web请求调用wcf方法。使用GET方法效果很好,但是当我尝试调用POST方法时,它无法正常工作。下面是我调用的代码。 错误是"远程服务器返回错误:(400)错误请求"

Code Snippter

       string postData = string.Format("Id={0}", "1");
        HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("http://localhost:4567/ClientService.svc/UpdateNotificationStatus");
        webRequest.Method = "POST";
        webRequest.ContentType = "application/x-www-urlencoded";
        webRequest.ContentLength = postData.Length;

        using (StreamWriter requestWriter2 = new StreamWriter(webRequest.GetRequestStream()))
        {
            requestWriter2.Write(postData);
        }

        using (StreamReader responseReader = new StreamReader(webRequest.GetResponse().GetResponseStream()))
        {
            // dumps the HTML from the response into a string variable
            postData = responseReader.ReadToEnd();
        }

以下是我在WCF服务中的操作合同。奇怪的是,当我从OperationContract中删除参数时,例如" ID",此方法有效。

    [OperationContract]
    [WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped, UriTemplate = "updateNotificationStatus")]
    void UpdateNotificationStatus(string Id);

    public void UpdateNotificationStatus(string Id)
    {
        try
        {                                

            wmas_subsDataContext dc = new wmas_subsDataContext();

            var ObjNotification = dc.tbPushNotifications.Where(p => p.ID == Convert.ToInt32(Id));

            if (ObjNotification.ToList().Count > 0)
            {
                ObjNotification.First().Status = "Completed";
            }

            dc.SubmitChanges();                
        }

        catch (Exception ex)
        {
            LogFile.WriteException(ex);
            throw ex;
        }
    }

0 个答案:

没有答案