开发Web服务REST

本文关键字:REST 服务 Web 开发 | 更新日期: 2023-09-27 18:17:54

我想在数据库PostgreSQL和asp中的Web应用程序之间开发一个Web服务restful CRUD。我看了很多例子和教程,但我没有找到解决方案。我在这里:我有一个服务"Service191",我可以通过Mozilla或WCF测试客户端调用:

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服务将在其中执行请求的表。我也有一个Handler:

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);
    }
}

但是我不明白为什么我的handler从来没有调用过。所以我总是有一个400的错误

我也有一个DAL类谁允许连接请求数据库:

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 id_entete=@id_entete, emmetteur=@emmetteur, destinataires=@destinataires, objet=@objet, contenu=@contenu, date_envoi=@date_envoi, heure_envoi=@heure_envoi WHERE id=@id";
                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 id=@id";
                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 context)做什么?谢谢你的帮助,很抱歉我的英语不好…! :)

开发Web服务REST

我在工作中经常使用这个页面:http://www.codeproject.com/Articles/112470/Developing-a-REST-Web-Service-using-C-A-walkthroug