【问题标题】:Posting an object via REST XML in C# WCF returns 400 Bad request在 C# WCF 中通过 REST XML 发布对象返回 400 Bad request
【发布时间】:2012-11-11 14:31:33
【问题描述】:

我正在尝试使用带有 XML 的 REST 将对象发布到 WCF 服务,但我不断收到 "error: (400) Bad Request" 抛出。我知道这个网站上有很多关于同样问题的帖子,但我似乎找不到解决方案。

我的 WCF 服务代码:

IPhoneBookService.cs:

    [OperationContract]
    [WebInvoke( UriTemplate = "/addentry/", 
                Method = "POST",
                BodyStyle = WebMessageBodyStyle.Bare, 
                RequestFormat = WebMessageFormat.Xml, 
                ResponseFormat = WebMessageFormat.Xml)]
    void AddEntry(Contact contact);

PhoneBookService.cs:

    DataPhonebookDataContext dc = new DataPhonebookDataContext();
    public void AddEntry(Contact contact)
    {
        if (contact == null)
        {
            throw new ArgumentNullException("contact");
        }
        dc.Contacts.InsertOnSubmit(contact);

        try
        {
            dc.SubmitChanges();
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
        }           

    }

客户端(ASP 页面)代码:

    private WebClient client = new WebClient();
    HttpWebRequest req;
    protected void Page_Load(object sender, EventArgs e)
    {
        req = (HttpWebRequest)WebRequest.Create("http://localhost:1853/PhoneBookService.svc/addentry/");
        req.Method = "POST";
        req.ContentType = "application/xml; charset=utf-8";
        req.Timeout = 30000;
        client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadStringCompleted);
    }
    protected void btnAddEntry_Click(object sender, EventArgs e)
    {
        var contact = new Contact(); //Contact class from WCF service reference
        contact.LastName = txtLastName.Text;
        contact.FirstName = txtFirstName.Text;
        contact.PhoneNumber = txtPhone.Text;

        //Code using Webclient
        //client.UploadData(new Uri("http://localhost:1853/PhoneBookService.svc/addentry/"), TToByteArray<Contact>(contact));

        //Code using webrequest
        byte[] buffer = TToByteArray<Contact>(contact);
        req.ContentLength = buffer.Length;
        Stream PostData = req.GetRequestStream();
        PostData.Write(buffer, 0, buffer.Length);
        PostData.Close();

        HttpWebResponse resp = req.GetResponse() as HttpWebResponse;
        Encoding enc = System.Text.Encoding.GetEncoding(1252);
        StreamReader loResponseStream =
        new StreamReader(resp.GetResponseStream(), enc);
        string response = loResponseStream.ReadToEnd();
    }
    private byte[] TToByteArray<T>(T item)
    {
        BinaryFormatter bf = new BinaryFormatter();
        MemoryStream ms = new MemoryStream();

        if (!typeof(T).IsSerializable)
        {
            throw new ArgumentException("The type of the argument must be serializable");
        }
        bf.Serialize(ms, item);
        return ms.ToArray();
    }

Contact 类在DataContext 中定义,由 LinqToSQL 类生成。我将Contact 类编辑为可序列化。

【问题讨论】:

  • 您能否指出代码中“错误请求”异常的确切行?
  • 如果你创建了一个监听 XML 格式的 post 请求的 web 服务,它只会响应 XML 格式的请求。你用二进制格式的数据喂它。我认为有你的问题。

标签: c# .net xml wcf rest


【解决方案1】:

您创建了一个监听 XML 发布请求的 Web 服务。这意味着请求消息格式必须是 XML。

另一方面,您的客户端以二进制格式序列化合约。尝试使用 XMLSerializer,而不是 BinaryFormatter。

WebMessageBodyStyle.Bare 属性不表示二进制数据。它仅表明消息没有包含在带有元信息的附加 XML 标记中。

如果你想在你的服务中接收二进制数据,你应该将输入参数声明为流,然后在服务器上不进行自动序列化,你会完全按照客户端发送的方式接收消息。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-27
    • 1970-01-01
    相关资源
    最近更新 更多