简体   繁体   English

在C#WCF中通过REST XML发布对象返回400错误请求

[英]Posting an object via REST XML in C# WCF returns 400 Bad request

I'm trying to Post an object to a WCF Service using REST with XML, but I keep getting the "error: (400) Bad Request" thrown. 我正在尝试使用带有XML的REST将对象发布到WCF服务,但是我不断收到"error: (400) Bad Request" I know there are a lot of posts on this site concerning the same problem, but I can't seem to find a solution. 我知道这个站点上有很多关于相同问题的文章,但是我似乎找不到解决方法。

My WCF service code: 我的WCF服务代码:

IPhoneBookService.cs: iPhoneBookService.cs:

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

PhoneBookService.cs: 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);
        }           

    }

Client (ASP page) code: 客户端(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();
    }

The Contact class is defined in the DataContext , witch is generated by a LinqToSQL class. Contact类是在DataContext定义的,它是由LinqToSQL类生成的。 I edited the Contact class to be serializable. 我将Contact类编辑为可序列化的。

You created a web service that listens to XML post requests. 您创建了一个侦听XML发布请求的Web服务。 This implies that the request message Format has to be XML. 这意味着请求消息格式必须为XML。

Your client on the other Hand serializes the contract in binary Format. 另一方面,您的客户以二进制格式序列化合同。 Try to use the XMLSerializer, not the BinaryFormatter. 尝试使用XMLSerializer,而不是BinaryFormatter。

The WebMessageBodyStyle.Bare attribute does not indicate binary data. WebMessageBodyStyle.Bare属性不指示二进制数据。 It only indicates that the message is not wrapped in additional XML tags with meta information. 它仅指示该消息未包装在带有元信息的其他XML标记中。

if you want to receive Binary data in your Service, you should declare the Input Parameter as Stream, then no automatic serialization is done on the Server and you receive the message exactly the way the client sent it. 如果要在服务中接收二进制数据,则应将输入参数声明为Stream,然后在服务器上不进行自动序列化,并且您将完全按照客户端发送消息的方式接收消息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM