2016-11-14 213 views
0

我想在數據庫PostgreSQL和Web應用程序之間開發一個Web服務平穩的CRUD。我看了很多示例和教程,但我沒有找到解決方案。我'在這裏: 我有一個服務 「Service191」 我可以通過Mozilla或通過WCF測試客戶端撥打:Developp Web服務REST

public class Service191 : IService191 
{ 
    public string data; 
    public static NpgsqlConnection conn; 

    /* 
    * Connection à la base de donnée 
    */ 
    public void connection() 
    { 
     try 
     { 
       Mails mail = new Mails(); 
       string strConnString = @"Server=194.206.X.XXX; Port=5432; Database=XXXXX; User Id=XXXX; Password=XXXXX"; 
       DAL.DAL dal = new DAL.DAL(strConnString); 

       //TestSelectCommand(mail, dal); 
       //TestXMLSerialization(); 


       GenerateGetRequest(); 
       //GeneratePostRequest(); 


     } 
     catch (Exception e) 
     { 
      MessageBox.Show(e.ToString()); 
     } 
    } 

爲了測試這個我調用函數GenerateGetRequest():

private static void GenerateGetRequest() 
    { 
     string url = "http://localhost:49761/Service191.svc/mails?id=14"; 
     HttpWebRequest GETRequest = (HttpWebRequest)WebRequest.Create(url); 
     GETRequest.Method = WebRequestMethods.Http.Get; 

     HttpWebResponse GETResponse = (HttpWebResponse)GETRequest.GetResponse(); 
     Stream GetResponseStream = GETResponse.GetResponseStream(); 
     StreamReader sr = new StreamReader(GetResponseStream); 

     MessageBox.Show(sr.ReadToEnd()); 
    } 

Url是我的Web應用程序稍後發送的內容。 「郵件」是Web服務將執行請求的表格。 我有太多處理程序:

public class Handler : IHttpHandler 
{ 
    private DAL.DAL dal; 
    private string connString; 
    private Mails mail; 
    private ErrorHandler.ErrorHandler errHandler; 

    #region HANDLER 

    public bool IsReusable 
    { 
     get 
     { 
      throw new NotImplementedException(); 
     } 
    } 

    public void ProcessRequest(HttpContext context) 
    { 
     try 
     { 
      string url = Convert.ToString(context.Request.Url); 
      connString = "Server = 194.206.X.XXX; Port = 5432; Database = XXXX; User Id = XXXX; Password = XXXXX"; 
      dal = new DAL.DAL(connString); 
      errHandler = new ErrorHandler.ErrorHandler(); 

      switch (context.Request.HttpMethod) 
      { 
       case "GET": 
        READ(context); 
        break; 
       case "POST": 
        CREATE(context); 
        break; 
       case "PUT": 
        UPDATE(context); 
        break; 
       case "DELETE": 
        DELETE(context); 
        break; 
       default: 
        break; 
      } 
     } 
     catch (Exception ex) 
     { 
      errHandler.ErrorMessage = ex.Message.ToString(); 
      context.Response.Write(errHandler.ErrorMessage); 
      //MessageBox.Show(ex.ToString()); 
     } 
    } 

    #endregion 

    #region CRUD 

    private void READ(HttpContext context) 
    { 
     try 
     { 
      int id = Convert.ToInt16(context.Request["id"]); 
      mail = dal.GetMail(id); 
      if (mail == null) 
       context.Response.Write(id + "No mail found"); 

      string serialized = Serialize(mail); 
      context.Response.ContentType = "text/xml"; 
      WriteResponse(serialized); 
      MessageBox.Show("mail READ"); 
     } 
     catch (Exception ex) 
     { 
      errHandler.ErrorMessage = dal.GetException(); 
      errHandler.ErrorMessage = ex.Message.ToString(); 
      //MessageBox.Show(ex.ToString()); 
     } 
    } 

    private void CREATE(HttpContext context) 
    { 
     try 
     { 
      byte[] PostData = context.Request.BinaryRead(context.Request.ContentLength); 
      string str = Encoding.UTF8.GetString(PostData); 
      Mails mail = Deserialize(PostData); 
      dal.AddMail(mail); 
      MessageBox.Show("mail CREATE"); 
     } 
     catch (Exception ex) 
     { 
      errHandler.ErrorMessage = dal.GetException(); 
      errHandler.ErrorMessage = ex.Message.ToString(); 
      //MessageBox.Show(ex.ToString()); 
     } 

    } 

    private void UPDATE(HttpContext context) 
    { 
     try 
     { 
      byte[] PUTRequestByte = context.Request.BinaryRead(context.Request.ContentLength); 
      context.Response.Write(PUTRequestByte); 

      Mails mail = Deserialize(PUTRequestByte); 
      dal.UpdateMail(mail); 
      MessageBox.Show("mail UPDATE"); 
     } 
     catch (Exception ex) 
     { 
      errHandler.ErrorMessage = dal.GetException(); 
      errHandler.ErrorMessage = ex.Message.ToString(); 
      //MessageBox.Show(ex.ToString()); 
     } 
    } 

    private void DELETE(HttpContext context) 
    { 
     try 
     { 
      int id = Convert.ToInt16(context.Request["id"]); 
      dal.DeleteMail(id); 
      MessageBox.Show("mail DELETE"); 
     } 
     catch (Exception ex) 
     { 
      errHandler.ErrorMessage = dal.GetException(); 
      errHandler.ErrorMessage = ex.Message.ToString(); 
     } 
    } 

    #endregion 

    private Mails Deserialize (byte[] xmlByteData) 
    { 
     try 
     { 
      XmlSerializer ds = new XmlSerializer(typeof(Mails)); 
      MemoryStream memoryStream = new MemoryStream(xmlByteData); 
      Mails mail = new Mails(); 
      mail = (Mails)ds.Deserialize(memoryStream); 
      return mail; 
     } 
     catch (Exception ex) 
     { 
      MessageBox.Show(ex.ToString()); 
      throw; 
     } 
    } 

    private static void WriteResponse(string strMessage) 
    { 
     HttpContext.Current.Response.Write(strMessage); 
    } 

    private String Serialize(Mails mail) 
    { 
     try 
     { 
      String XmlizedString = null; 
      XmlSerializer xs = new XmlSerializer(typeof(Mails)); 
      MemoryStream memoryStream = new MemoryStream(); 
      XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8); 
      xs.Serialize(xmlTextWriter, mail); 
      memoryStream = (MemoryStream)xmlTextWriter.BaseStream; 
      XmlizedString = UTF8ByteArrayToString(memoryStream.ToArray()); 
      return XmlizedString; 
     } 
     catch (Exception ex) 
     { 
      MessageBox.Show(ex.ToString()); 
      throw; 
     } 
    } 

    private String UTF8ByteArrayToString(Byte[] characters) 
    { 
     UTF8Encoding encoding = new UTF8Encoding(); 
     String constructedString = encoding.GetString(characters); 
     return (constructedString); 
    } 
} 

但我不明白爲什麼我的處理程序不調用。所以我一直有400錯誤。

我有太多一個DAL類誰permiss連接等請求到數據庫:

public class DAL 
{ 
    private NpgsqlConnection conn; 
    private NpgsqlCommand command; 
    private static string connString; 
    private static List<Mails> mailList; 
    private ErrorHandler.ErrorHandler err; 

    public DAL(string _connString) 
    { 
     err = new ErrorHandler.ErrorHandler(); 
     connString = _connString; 
    } 

    public void AddMail (Mails mail) 
    { 
     try 
     { 
      using (conn) 
      { 
       string npgsqlInsertString = "INSERT INTO mails (id_entete, emmetteur, destinataires, objet, contenu, date_envoi, heure_envoi) VALUES (@id_entete, @emmetteur, @destinataires, @objet, @contenu, @date_envoi, @heure_envoi)"; 

       conn = new NpgsqlConnection(connString); 

       command = new NpgsqlCommand(); 
       command.Connection = conn; 
       command.Connection.Open(); 
       command.CommandText = npgsqlInsertString; 

       NpgsqlParameter idParam = new NpgsqlParameter("@id_entete", mail.Id_entete); 
       NpgsqlParameter emmParam = new NpgsqlParameter("@id_entete", mail.Emmetteur); 
       NpgsqlParameter destParam = new NpgsqlParameter("@id_entete", mail.Destinataires); 
       NpgsqlParameter objParam = new NpgsqlParameter("@id_entete", mail.Objet); 
       NpgsqlParameter contParam = new NpgsqlParameter("@id_entete", mail.Contenu); 
       NpgsqlParameter dateParam = new NpgsqlParameter("@id_entete", mail.Date_envoi); 
       NpgsqlParameter heureParam = new NpgsqlParameter("@id_entete", mail.Heure_envoi); 

       command.Parameters.AddRange(new NpgsqlParameter[] { idParam, emmParam, destParam, objParam, contParam, dateParam, heureParam }); 
       command.ExecuteNonQuery(); 
       command.Connection.Close(); 

      } 
     } 
     catch (Exception ex) 
     { 
      MessageBox.Show(ex.ToString()); 
     } 
    } 

    public void UpdateMail (Mails mail) 
    { 
     try 
     { 
      using (conn) 
      { 
       string npgsqlUpdateString = "UPDATE mails SET [email protected]_entete, [email protected], [email protected], [email protected], [email protected], [email protected]_envoi, [email protected]_envoi WHERE [email protected]"; 

       conn = new NpgsqlConnection(connString); 

       command = new NpgsqlCommand(); 
       command.Connection = conn; 
       command.Connection.Open(); 
       command.CommandText = npgsqlUpdateString; 

       NpgsqlParameter idParam = new NpgsqlParameter("@id_entete", mail.Id_entete); 
       NpgsqlParameter emmParam = new NpgsqlParameter("@id_entete", mail.Emmetteur); 
       NpgsqlParameter destParam = new NpgsqlParameter("@id_entete", mail.Destinataires); 
       NpgsqlParameter objParam = new NpgsqlParameter("@id_entete", mail.Objet); 
       NpgsqlParameter contParam = new NpgsqlParameter("@id_entete", mail.Contenu); 
       NpgsqlParameter dateParam = new NpgsqlParameter("@id_entete", mail.Date_envoi); 
       NpgsqlParameter heureParam = new NpgsqlParameter("@id_entete", mail.Heure_envoi); 

       command.Parameters.AddRange(new NpgsqlParameter[] { idParam, emmParam, destParam, objParam, contParam, dateParam, heureParam }); 
       command.ExecuteNonQuery(); 
       command.Connection.Close(); 
      } 
     } 
     catch (Exception ex) 
     { 
      err.ErrorMessage = ex.Message.ToString(); 
      throw; 
     } 
    } 

    public void DeleteMail (int id) 
    { 
     try 
     { 
      using (conn) 
      { 
       string npgsqlDeleteString = "DELETE FROM mails WHERE [email protected]"; 

       conn = new NpgsqlConnection(connString); 

       command = new NpgsqlCommand(); 
       command.Connection = conn; 
       command.Connection.Open(); 
       command.CommandText = npgsqlDeleteString; 

       NpgsqlParameter idParam = new NpgsqlParameter("@id", id); 
       command.Parameters.Add(idParam); 
       command.ExecuteNonQuery(); 
       command.Connection.Close(); 
      } 
     } 
     catch (Exception ex) 
     { 
      err.ErrorMessage = ex.Message.ToString(); 
      throw; 
     } 
    } 

    public Mails GetMail(int ID) 
    { 
     try 
     { 
      if (mailList == null) 
      { 
       mailList = GetMails(); 
      } 
      foreach (Mails mail in mailList) 
      { 
       if (mail.Id == ID) 
       { 
        return mail; 
       } 
      } 
      return null; 
     } 
     catch (Exception ex) 
     { 
      //MessageBox.Show(ex.ToString()); 
      err.ErrorMessage = ex.Message.ToString(); 
      throw; 
     } 
    } 

    private List<Mails> GetMails() 
    { 
     try 
     { 
      using (conn) 
      { 
       mailList = new List<Mails>(); 

       conn = new NpgsqlConnection(connString); 
       string npgsqlSelectString = "SELECT * FROM mails"; 
       command = new NpgsqlCommand(npgsqlSelectString, conn); 
       command.Connection.Open(); 

       NpgsqlDataReader reader = command.ExecuteReader(); 
       while (reader.Read()) 
       { 
        Mails mail = new Mails(); 
        mail.Id = (int)reader[0]; 
        mail.Id_entete = (int)reader[1]; 
        mail.Emmetteur = reader[2].ToString().Replace(" ", ""); 
        mail.Destinataires = reader[3].ToString().Replace(" ", ""); 
        mail.Objet = reader[4].ToString().Replace(" ", ""); 
        mail.Contenu = reader[5].ToString().Replace(" ", ""); 
        mail.Date_envoi = reader[6].ToString().Replace(" ", ""); 
        mail.Heure_envoi = reader[7].ToString().Replace(" ", ""); 
        mailList.Add(mail); 
       } 
       command.Connection.Close(); 
       return mailList; 
      } 
     } 
     catch (Exception ex) 
     { 
      //MessageBox.Show(ex.ToString()); 
      err.ErrorMessage = ex.Message.ToString(); 
      throw; 
     } 
    } 

    public string GetException() 
    { 
     return err.ErrorMessage.ToString(); 
    } 
} 

那麼,誰可以爲我做調用函數的ProcessRequest(HttpContext的背景下)?感謝您的幫助,併爲我的壞英語而感到難過......! :)

+0

你註冊了你的HttpHandler嗎? [如何註冊HTTP處理程序](https://msdn.microsoft.com/en-us/library/46c5ddfy.aspx) – jadarnel27

+0

此處您的代碼太多了。你需要把它燒到一個[MCVE](http://stackoverflow.com/help/mcve)。 – mason

+0

是的,但我不知道它是否工作。因爲在IIS管理器中,我在默認網站中看到了我的Web服務,但我無法添加應用程序擴展名映射。 –

回答