尝试执行HTTP POST时出现错误请求400错误

时间:2009-10-14 05:19:26

标签: wcf http rest post

我编写了一个WCF REST服务,如下所示

namespace UserService
{
    // TODO: Modify the service behavior settings (instancing, concurrency etc) based on the service's requirements. Use ConcurrencyMode.Multiple if your service implementation
    //       is thread-safe.
    // TODO: Please set IncludeExceptionDetailInFaults to false in production environments
    [ServiceBehavior(IncludeExceptionDetailInFaults = true, InstanceContextMode = InstanceContextMode.PerCall, ConcurrencyMode = ConcurrencyMode.Single)]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    [ServiceContract]
    public class Service 
    {
        UserManager userManager = new UserManager();

        [OperationContract]
        [WebGet(UriTemplate = "{userName}")]
        [WebHelp(Comment = "Gets an user object given the username")]
        public User GetUser(string userName)
        {
            return userManager.Read(userName);
        }

        [OperationContract]
        [WebInvoke(Method = "POST", UriTemplate = "", RequestFormat=WebMessageFormat.Xml, ResponseFormat=WebMessageFormat.Xml, BodyStyle=WebMessageBodyStyle.Bare)]
        [WebHelp(Comment = "Creates an User")]
        public void CreateUser(User user)
        {
            userManager.Create(user);
        }
    }

}

我从我的ASP.NET应用程序中访问它,如下所示。

HttpClient client = new HttpClient();


        HttpContent content = null;

            DiscussionForum.Library.User user = new User();
            user.UserEmailAddress = emailAddressTextBox.Text;
            user.UserName = userNameTextBox.Text;
            user.UserPassword = passwordTextBox.Text;

            content = HttpContentExtensions.CreateXmlSerializable<DiscussionForum.Library.User>(user);
            content.LoadIntoBuffer();


            HttpResponseMessage response = client.Post(new Uri("http://localhost/UserService/Service.svc"),"application/xml", content);

            Response.Write(response.StatusCode.ToString());

我在客户端的状态代码中收到Badrequest 400。

我错过了什么吗?

1 个答案:

答案 0 :(得分:0)

嗯,我立刻看到的一件事是你的服务使用DataContractSerializer而你的客户端使用XmlSerializer,所以“User”类型的XML表示可能不一样。

要么使用服务上的 [XmlSerializerFormat] 属性,要么在客户端上使用 HttpContentExtensions.CreateDataContract (当然不能同时使用<)>

但我并非100%确定这是你的问题(或唯一的问题)......如果不是,请回复此处,我可以提供一些调试技巧。