示例#1
0
        Nancy.Response AddUser()
        {
            // capture actual string posted in case the bind fails (as it will if the JSON is bad)
            // need to do it now as the bind operation will remove the data
            String rawBody = this.GetRawBody();

            UserModel user = this.Bind <UserModel>();

            // Reject request with an ID param
            if (user.Id != null)
            {
                return(ErrorBuilder.ErrorResponse(this.Request.Url.ToString(), "POST", HttpStatusCode.Conflict, String.Format("Use PUT to update an existing user with Id = {0}", user.Id)));
            }

            // Save the item to the DB
            try {
                UserMapper usr_mpr = new UserMapper();
                user.CreateId();
                usr_mpr.Add(user);

                //Get new user data from DB
                UserModel      new_user = usr_mpr.GetById(user.Id);
                Nancy.Response response = Response.AsJson(new_user);
                response.StatusCode = HttpStatusCode.Created;

                string uri = this.Request.Url.SiteBase + this.Request.Path + "/" + user.Id;
                response.Headers["Location"] = uri;

                return(response);
            } catch (Exception e) {
                Console.WriteLine(rawBody);
                String operation = String.Format("UserModule.AddItem({0})", (user == null) ? "No Model Data" : user.Username);
                return(HandleException(e, operation));
            }
        }