使用POSTMAN

时间:2017-12-10 10:36:57

标签: c# xml

所以我在使用C#和POSTMAN的POST方法时遇到了麻烦。 GET工作得很好,但我在POST方法上遇到错误。 这是我的代码:

public SaveProfileResponseDTO SaveProfileQuery(SaveProfileRequestDTO objProfileRequest)
    {
       SaveProfileResponseDTO objSaveProfileResponse;
       try
       {
           XElement xElement = XElement.Load(Path);

           XElement Student = (from u in xElement.Elements("Student")
                       where (string)u.Attribute("id") == objProfileRequest.StudentID.ToString()
                       select (u)).FirstOrDefault();

           Student.Element("Name").Value = objProfileRequest.Name;
           Student.Element("Gender").Value = objProfileRequest.Gender;

           xElement.Save(Path);

           objSaveProfileResponse = new SaveProfileResponseDTO()
           {
               Status = new ResponseCode()
               {
                   Code = StatusCodes.Success,
                   Message = StatusMessages.Success
               }
           };
       }
       catch (Exception ex)
       {
           objSaveProfileResponse = new SaveProfileResponseDTO()
           {
               Status = new ResponseCode()
               {
                   Code = StatusCodes.Error,
                   Message = StatusMessages.Error
               }
           };
       }
       return objSaveProfileResponse;
    }

这是我的控制器:

       [Route("Profile")]
    [HttpPost]
    public HttpResponseMessage Profile(SaveProfileRequestModel objSaveProfileRequestModel)
    {
        StudentManager = new StudentManager();
        SaveProfileRequestDTO objSaveProfileRequestDTO = new SaveProfileRequestDTO()
        {
            Gender = objSaveProfileRequestModel.Gender,
            Name = objSaveProfileRequestModel.Name,
            StudentID = objSaveProfileRequestModel.StudentID
        };
        SaveProfileResponseDTO objSavePofileResponse = StudentManager.SaveProfile(objSaveProfileRequestDTO);
        SaveProfileResponseModel objSaveProfileResponseModel = new SaveProfileResponseModel()
        {
            Status = objSavePofileResponse.Status
        };
        return Request.CreateResponse(HttpStatusCode.OK, objSavePofileResponse);
    }

任何帮助将不胜感激。 如果你愿意,我也可以提供GET方法代码。 提前谢谢。

1 个答案:

答案 0 :(得分:1)

           XElement Student = (from u in xElement.Elements("Student")
                   where (string)u.Attribute("id") == objProfileRequest.StudentID.ToString()
                   select (u)).FirstOrDefault();

           Student.Element("Name").Value = objProfileRequest.Name;

如果XML文件中没有与您传入的ID匹配的学生,则最后一行将导致NullReferenceException。