JSON C#Web服务创建和测试?

时间:2014-05-25 09:14:17

标签: c# mysql json web-services

我正在尝试创建JSON WCF Web服务。 我真的完全不了解整个过程!我正在连接到服务器上的MySQL数据库。 所以我有以下代码: 我的界面 -

    [ServiceContract]
    public interface IService1
    {
        [OperationContract]
        [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped, UriTemplate = "/GetAllResources")]
        List<Resources> GetAllResources();


        [OperationContract]
        [WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped, UriTemplate = "/AddRoom")]
        void AddRoom(string location, string name);
...

我的服务 -

[ScriptService]
        public class Service1 : IService1
    {

            [WebMethod]
            [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
            public void AddRoom(string location, string name)
            {
                String conString = System.Configuration.ConfigurationManager.ConnectionStrings["MyDatabaseConnectionString"].ConnectionString;
                using (MySqlConnection cnn = new MySqlConnection(conString))
                {
                    cnn.Open();
                    String sql = String.Format("INSERT INTO rooms(roomLocation, roomName) VALUES ({0}, {1});", location, name);
                    MySqlCommand cmd = new MySqlCommand(sql, cnn);
                    //doesn't return any rows
                    cmd.ExecuteNonQuery();
                }              
            }

            [WebMethod]
            [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
            public List<Resources> GetAllResources()
            {
                String conString = System.Configuration.ConfigurationManager.ConnectionStrings["MyDatabaseConnectionString"].ConnectionString;
                List<Resources> al = new List<Resources>();
                using (MySqlConnection cnn = new MySqlConnection(conString))
                {
                    cnn.Open();
                    String sql = String.Format("select * from resources");
                    MySqlCommand cmd = new MySqlCommand(sql, cnn);
                    MySqlDataReader reader = cmd.ExecuteReader();

                    while (reader.Read())
                    {
                        al.Add((Resources)reader[0]);
                    }
                    return al;
                }
            }
...

Web配置 -

...
<system.web.extensions>
    <scripting>
      <webServices>
        <jsonSerialization maxJsonLength="5000"/>
      </webServices>
    </scripting>
  </system.web.extensions>
  <system.web>
    <compilation debug="true" targetFramework="4.5" />
    <httpRuntime targetFramework="4.5"/>
  </system.web>
  <system.serviceModel>
    <services>
      <service name="RoomBookingService.Service1" behaviorConfiguration="RoomBookingServiceBehavior">
        <endpoint address="../Service1.svc"
            binding="webHttpBinding"
            contract="RoomBookingService.IService1"
            behaviorConfiguration="webBehaviour" />
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="RoomBookingServiceBehavior">
          <!-- To avoid disclosing metadata information, set the values below to false before deployment -->
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
          <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
          <serviceDebug includeExceptionDetailInFaults="false"/>
        </behavior>
      </serviceBehaviors>
      <endpointBehaviors>
        <behavior name="webBehaviour">
          <webHttp automaticFormatSelectionEnabled="true"/>
        </behavior>
      </endpointBehaviors>
    </behaviors>
...

这是对的吗?我可以使用哪些工具来测试服务?我已将它放到服务器上并尝试下载一些测试工具,但是他们没有给我任何错误,只是因为它没有返回JSON?!

我将创建一个与该服务交谈的Android应用程序,但由于这也是一个学习曲线,我想知道我的服务在添加另一层复杂性之前正常工作。

对我的代码或我的问题的任何帮助或评论将不胜感激。 谢谢你的时间

1 个答案:

答案 0 :(得分:0)

我设法让它工作: 这是我的代码: 的合同:

    namespace RoomBookingService
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IService1" in both code and config file together.
    [ServiceContract]
    public interface IService1
    {
        [OperationContract]
        [WebGet(ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped, UriTemplate = "GetAllResources")]
        String GetAllResources();

<强>服务

[WebMethod]
            [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public String GetAllResources()
            {
                String conString = System.Configuration.ConfigurationManager.ConnectionStrings["MyDatabaseConnectionString"].ConnectionString;
                List<Dictionary<string, object>> tableRows = new List<Dictionary<string, object>>();
                Dictionary<string, object> row= new Dictionary<string,object>();
                DataTable dt = new DataTable();
                System.Web.Script.Serialization.JavaScriptSerializer serializer =
          new System.Web.Script.Serialization.JavaScriptSerializer();

                try
                {
                    using (MySqlConnection cnn = new MySqlConnection(conString))
                                    {                                        
                                        cnn.Open();
                                        String sql = String.Format("select resourceID, resourceName, resourceDesc, roomID from resources");
                                        MySqlCommand cmd = new MySqlCommand(sql, cnn);
                                        MySqlDataReader reader = cmd.ExecuteReader();
                                        dt.Load(reader);

                                        foreach (DataRow dr in dt.Rows)
                                        {
                                            row = new Dictionary<String, Object>();
                                            foreach (DataColumn col in dt.Columns)
                                            {
                                                row.Add(col.ColumnName, dr[col]);
                                            }
                                            tableRows.Add(row);
                                        }
                                        return serializer.Serialize(tableRows);
                                    }
                }
                catch (Exception ex)
                {
                    return ex.ToString();
                }            
            }

<强> WebConfig

 <system.web.extensions>
    <scripting>
      <webServices>
        <jsonSerialization maxJsonLength="5000"/>
      </webServices>
    </scripting>
  </system.web.extensions>
  <system.web>
    <compilation debug="true" targetFramework="4.5" />
    <httpRuntime targetFramework="4.5"/>
  </system.web>
  <system.serviceModel>
    <services>
      <service name="RoomBookingService.Service1" behaviorConfiguration="RoomBookingServiceBehavior">
        <endpoint address=""
            binding="webHttpBinding"
            contract="RoomBookingService.IService1"
            behaviorConfiguration="webBehaviour" />
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="RoomBookingServiceBehavior">
          <!-- To avoid disclosing metadata information, set the values below to false before deployment -->
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
          <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
          <serviceDebug includeExceptionDetailInFaults="false"/>
        </behavior>
      </serviceBehaviors>
      <endpointBehaviors>
        <behavior name="webBehaviour">
          <webHttp automaticFormatSelectionEnabled="true"/>
        </behavior>
      </endpointBehaviors>

除了它的工作之外,还不是绝对清楚!所以我会说: - )

谢谢!