2

I have a wcf 3.5 restful web service that is hosted in IIS 7.5. It is setup to use Basic Authentication over https. I added as much information as possible below (names of classes, etc have been altered slightly). Any advice or suggestions are greatly appreciated.

Every time I try to send a POST either via Fiddler or through a client application I get this message:

HTTP/1.1 400 Bad Request

I turned on the svctrace logs give me this information:

System.Runtime.Serialization.SerializationException, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089

Unable to deserialize XML body with root name 'user-search-request' and root namespace '' (for operation 'FetchMatchingUsers' and contract ('IMyService', 'http://tempuri.org/')) using DataContractSerializer. Ensure that the type corresponding to the XML is added to the known types collection of the service.

The URL for the service looks like this: https://mysite.com/program/user/v1.0/MyService.svc

My Service Contract looks like this:

[ServiceContract]
interface IMyService
{       
    [WebInvoke(UriTemplate = "",
               Method = "POST",
               RequestFormat = WebMessageFormat.Xml,
               ResponseFormat = WebMessageFormat.Xml)]
    [OperationContract]
    Users FetchMatchingUsers(User u);
}

My Service Implementation looks like this:

[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
public class MyService : IMyService
{
    static Users _users = new Users();
    public Users FetchMatchingUsers(User u)
    {
              return SearchByFullName(u.FirstName, u.LastName);


    }
}

The DataContract looks like this:

[CollectionDataContract(Name = "user-search-request", Namespace = "")]
public class Users : List<User>
{ }

[DataContract(Name = "user", Namespace = "")]
public class User
{

    [DataMember(Name = "first-name")]
    public string FirstName { get; set; }

    [DataMember(Name = "last-name")]
    public string LastName { get; set; }
 }

Service Model is setup like this:

    <system.serviceModel>
<diagnostics>
  <messageLogging logMalformedMessages="true" logMessagesAtTransportLevel="true" />
</diagnostics>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true">
</serviceHostingEnvironment>

<services>
  <service behaviorConfiguration="basic" name="MyService">
    <clear />
    <endpoint address="/program/user/v1.0" binding="basicHttpBinding"
      name="Default" contract="MyService.IMyService"
      listenUriMode="Explicit">
      <identity>
        <certificateReference storeName="My" storeLocation="LocalMachine"
          x509FindType="FindBySubjectDistinguishedName" />
      </identity>
    </endpoint> 
    <host>
      <baseAddresses>
        <add baseAddress="https://mysite.com" />
      </baseAddresses>
    </host>
  </service>
</services>
<behaviors>
  <serviceBehaviors>
    <behavior name="basic">
      <serviceMetadata httpsGetEnabled="true"/>
      <serviceDebug includeExceptionDetailInFaults="false"/>
    </behavior>
  </serviceBehaviors>
</behaviors>
<bindings>
  <basicHttpBinding>
    <binding name="basicHttpBinding">
      <readerQuotas maxStringContentLength="10500" />
      <security mode="Transport">
        <transport clientCredentialType="Basic" />
      </security>
    </binding>
  </basicHttpBinding>
</bindings>

My POST is setup like this:

    private void DoPost

    {  
        String firstname = "Test";
        String lastname = "User";
        User user = new User();
        user.FirstName = firstname;
        user.LastName = lastname;


        String uristring = @"https://mysite.com/program/user/v1.0/MyService.svc/";

        Uri uri = new Uri(uristring);

        HttpWebRequest client = (WebRequest.Create(uri)) as HttpWebRequest;

        NetworkCredential cred = new NetworkCredential(_username, _password, _domain);
        String username = cred.Domain + "\\" + cred.UserName;
        byte[] credentialBuffer = new UTF8Encoding().GetBytes(username + ":" + cred.Password);

        client.Credentials = cred;
        client.Method = "POST";
        client.ContentType = "application/xml";
        client.Headers["Authorization"] = "Basic " + Convert.ToBase64String(credentialBuffer);


        List<User> users = new List<User>();
        users.Add(user);

 SerializeUsers sa = new SerializeUsers();
        String output = sa.SerializeUsers(users);


        client.ContentLength = output.Length;

        // Write the request StreamWriter 
        StreamWriter requestWriter = new StreamWriter(client.GetRequestStream(), System.Text.Encoding.ASCII);
        requestWriter.Write(output.ToString());
        requestWriter.Close();
        // Do the request to get the response 
        try
        {
            StreamReader responseReader = new StreamReader(client.GetResponse().GetResponseStream());
            String response = responseReader.ReadToEnd();
            responseReader.Close();
        }
        catch (WebException ex)
        {
            String message = ex.Message;
        }


    }

My Deserializer right now is just a test so the xml is actually hardcoded but I do need to make it work the right way once I get this problem solved.

    public class SerializeUsers
{
    public String SerializeUsers(List<User> ts)
    {
        String xml = @"<user-search-request xmlns:i=""http://www.w3.org/2001/XMLSchema-instance"">";
        foreach (User t in ts)
        {
            xml += @"<user>";

            xml += @"<first-name>" + t.FirstName + "</first-name>";
            xml += @"<last-name>" + t.LastName + "</last-name></user>";



        }

        xml += @"</user-search-request>";


        return xml;
    }
}

1 Answer 1

0

Hello can you try [XmlSerializerFormat] under your service contract so it should look like this:

[ServiceContract]
[XmlSerializerFormat]
interface IMyService

The second thing you might want to do is add a wrapper to your POST like so:

[WebInvoke(UriTemplate = "",
           Method = "POST",
           BodyStyle = WebMessageBodyStyle.Wrapped,
           RequestFormat = WebMessageFormat.Xml,
           ResponseFormat = WebMessageFormat.Xml)]

Failing that then your config file is to blame if I was to hazard a guess, it should be set up with webHttpBinding.

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.