mercredi 15 août 2018

Sending PUT request with object parameter (.NET WCF service)

So, there's my question.

I am currently working on a WCF REST Service, and I need now to implement a method that allows me to create an account (user account). Searching on the Web didn't help me this time, that's why I'm asking someone who really know what I mean x).

So, this is my method :

[WebInvoke(Method = "PUT", UriTemplate = "users/{username}", 
    RequestFormat = WebMessageFormat.Xml)]
    [OperationContract]
    void PutUserAccount(string username, User u)
    {
        Debug.WriteLine("Entering method [PutUserAccount]");
        // Check if user exists
        User user = DBManager.FindUser(username);
        if (user == null)
        {
            try
            {
                //Create or update new user
                u.Id = GetUserLink(username);
                u.Notes = GetUserNotesLink(username);
                u.BlackListed = false;
                DBManager.AddUser(u);

                // Set status to created and include new URI in Location 
                //header
                WebOperationContext.Current.OutgoingResponse.SetStatusAsCreated(GetUserProfile(username).Id);
            }
            catch (Exception e)
            {
                Debug.WriteLine("_PutUserAccount || Exception [" + e.Message + "]");
            }
        }
        else if (!DBManager.IsUserAuthorized(username, WebOperationContext.Current))
        {
            Debug.WriteLine("_PutUserAccount - 1. This user isn't allowed to add users");
            WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.Unauthorized;
            return;
        }
    }

And this is my "User" class :

[DataContract]
class _User
{
    [DataMember]
    public string Id { get; set; }
    [DataMember]
    public string Username { get; set; }
    [DataMember]
    public string Password { get; set; }
    [DataMember]
    public string Name { get; set; }
    [DataMember]
    public string Email { get; set; }
    [DataMember]
    public string Notes { get; set; }
    [DataMember]
    public bool BlackListed { get; set; }
}

And the problem is: I can't do any request to fill "User u" it always returns these exceptions :

Exception thrown: 'System.InvalidOperationException' in 
System.ServiceModel.Web.dll
Exception thrown: 'System.InvalidOperationException' in 
System.ServiceModel.dll
Exception thrown: 'System.InvalidOperationException' in 
System.ServiceModel.dll
Exception thrown: 'System.InvalidOperationException' in 
System.ServiceModel.dll

My question is, how do I have to build the request to pass a User to my Service ?

P.S. : I am using postman to test my code.




Aucun commentaire:

Enregistrer un commentaire