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

标签 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;
                }
            }
...

网络配置 -

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

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

最佳答案

我设法让它工作: 这是我的代码: 契约(Contract):

    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>

仍然不是完全清楚一切,但它正在工作!所以我会同意:-)

谢谢!

关于c# - JSON C# Web 服务创建和测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23853745/

相关文章:

java - 从 JSONArray 获取无名 JSON 中的特定项目

c# - 使用 System.IO 在 C# 中复制文件夹

c# - Linq中没有AsEnumerable()的本地方法

mysql - 每月交易次数(自 2014 年至 2016 年)

javascript - 如何在 AngularJs 中将 json 数组转换为 js 数组?

javascript - 如何验证 servertimestamp 是否小于 Firebase 本身的某个值?

c# - Dapper 存储过程的表值参数

C# windows 形成奇怪的行为

php - 警告 : mysql_fetch_array(): supplied argument is not a valid MySQL result resource

java - Spring Boot中如何使用ORDER BY?