JSON c# Web服务创建和测试

本文关键字:测试 创建 服务 Web JSON | 更新日期: 2023-09-27 18:05:16

我正在尝试创建一个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);
...

My Service -

[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应用程序来与服务对话,但这也将是一个学习曲线,我想知道我的服务在添加另一层复杂性之前是否正常工作。

任何帮助或评论我的代码或我的问题将非常感谢。感谢您的宝贵时间

JSON c# Web服务创建和测试

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

    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>

仍然不是完全清楚的一切,但它的工作!!所以我就用这个:-)

谢谢!