4

我正在测试如何从 Web 服务中的 SQL Server 检索数据。我在 VS 2010 中使用 SQL Server 2008 R2、asp.net Web 服务应用程序项目模板。

假设我有一个有 4 列且没有任何约束的表(为了对话)。

  • 电子邮件
  • 大学

如果用户输入 FirstName 的值,我希望能够获取我的 SQL 表的所有值。稍后我会将 FirstName 更改为 NTID 或一些有意义的列。现在,如果用户输入 FirstName,我的 Web 服务只返回单个值,比如说 LastName。

作为 Web 服务的新手,我正在努力学习尽可能多的知识,并且非常感谢您在帮助我时所付出的时间和精力。TIA。

我在哪里/如何在下面的代码中进行更改

这是我的数据助手类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;

namespace EmployeeRecs
{
    public class DataHelper
    {
        //create new method to get Employee record based on First Name
        public static string GetEmployee(string firstName)
        {
            string LastName = "";

            //Create Connection
            SqlConnection con = new SqlConnection (@"Data Source=myDBServer;Initial Catalog=MyDataBase;Integrated Security=true;");

            //Sql Command
            SqlCommand cmd = new SqlCommand("Select LastName from Employees where FirstName ='" + firstName.ToUpper() + "'", con);

            //Open Connection
            con.Open();

            //To Read From SQL Server
            SqlDataReader dr = cmd.ExecuteReader();

                while (dr.Read())
                {
                    LastName = dr["LastName"].ToString();
                }

            //Close Connection
                dr.Close();
                con.Close();

            return LastName;


        }

    }
}

这是我的 asmx.cs 课程

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;

namespace EmployeeRecs
{
    /// <summary>
    /// Summary description for Service1
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    // [System.Web.Script.Services.ScriptService]
    public class Service1 : System.Web.Services.WebService
    {

               //Create new web method to get Employee last name
        [WebMethod]
        public string GetEmployee(string firstName)
        {
            return DataHelper.GetEmployee(firstName);

        }
    }
}
4

1 回答 1

10

除了 SQL 注入之外,还有一些事情:

创建 DataContract 并为要返回的数据创建模型

[DataContract]
public class Employee
{
    [DataMember]
    public int NTID { get; set; }

    [DataMember]
    public string LastName { get; set; }

    [DataMember]
    public int FirstName { get; set; }
}

用您的 SQL 查询结果填充该模型并从您的服务中返回它

    //create new method to get Employee record based on First Name
    public static List<Employee> GetEmployee(string firstName)
    {
        //Create Connection
        SqlConnection con = new SqlConnection (@"Data Source=myDBServer;Initial Catalog=MyDataBase;Integrated Security=true;");

        //Sql Command
        SqlCommand cmd = new SqlCommand("Select NTID, LastName, FirstName from Employees where FirstName ='" + firstName.ToUpper() + "'", con);

        //Open Connection
        con.Open();

        List<Employee> employees = new List<Employee>();

        //To Read From SQL Server
        SqlDataReader dr = cmd.ExecuteReader();

        while (dr.Read())
        {
            var employee = new Employee { 
                       NTID = dr["NTID"].ToString();
                       LastName = dr["LastName"].ToString();
                       FirstName = dr["FirstName"].ToString();
                    };
            employees.Add(employee);
        }
        //Close Connection
        dr.Close();
        con.Close();
        return employees;
}

暴露它:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;

namespace EmployeeRecs
{
    /// <summary>
    /// Summary description for Service1
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    // [System.Web.Script.Services.ScriptService]
    public class Service1 : System.Web.Services.WebService
    {

               //Create new web method to get Employee last name
        [WebMethod]
        public List<Employee> GetEmployee(string firstName)
        {
            return DataHelper.GetEmployee(firstName);

        }
    }
}

来自 OP 的完整代码供后代使用:

这可能对其他在相同情况下苦苦挣扎的人有用。所以我发布了我的解决方案代码:在 VS 2010 中创建一个新的 WCF 项目,我使用 .net 版本 3.5 并在 WCF 模板下选择了 WCF 服务库。

这是我在 IService1.cs 下的代码

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Runtime.Serialization; 
using System.ServiceModel; 
using System.Text; 

namespace WcfServiceLibrary1 
{ 
    // 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] 
        List<Employee> GetEmployee(string firstName); 


        [OperationContract] 
        CompositeType GetDataUsingDataContract(CompositeType composite); 

        // TODO: Add your service operations here 
    } 


    //Custon Data contract 

    [DataContract] 
    public class Employee 
    { 
        [DataMember] 
        public string FirstName { get; set; } 

        [DataMember] 
        public string LastName { get; set; } 

        [DataMember] 
        public string Email { get; set; } 

        [DataMember] 
        public string University { get; set; } 

    }  



    // Use a data contract as illustrated in the sample below to add composite types to service operations 
    [DataContract] 
    public class CompositeType 
    { 
        bool boolValue = true; 
        string stringValue = "Hello "; 

        [DataMember] 
        public bool BoolValue 
        { 
            get { return boolValue; } 
            set { boolValue = value; } 
        } 

        [DataMember] 
        public string StringValue 
        { 
            get { return stringValue; } 
            set { stringValue = value; } 
        } 
    } 
} 

这是我在 Service1.cs 下的代码

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Runtime.Serialization; 
using System.ServiceModel; 
using System.Text; 
using System.Data; 
using System.Data.SqlClient; 

namespace WcfServiceLibrary1 
{ 
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in both code and config file together. 
    public class Service1 : IService1 
    { 
        public List<Employee> GetEmployee(string firstName)  

        { 
            //Create Connection  
            SqlConnection con = new SqlConnection(@"Data Source=gsops4;Initial Catalog=MultiTabDataAnalysis;Integrated Security=true;"); 

            //Sql Command  
            SqlCommand cmd = new SqlCommand("Select LastName, FirstName, Email, University from Employees where FirstName ='" + firstName.ToUpper() + "'", con); 

            //Open Connection  
            con.Open(); 

            List<Employee> employees = new List<Employee>(); 

            //To Read From SQL Server  
            SqlDataReader dr = cmd.ExecuteReader();  


            while (dr.Read())  
        {  
            var employee = new Employee {   

                       FirstName = dr["FirstName"].ToString(),  
                       LastName = dr["LastName"].ToString(), 
                       Email = dr["Email"].ToString(), 
                       University = dr["University"].ToString() 



                    };  
            employees.Add(employee);  
        }  
        //Close Connection  
        dr.Close();  
        con.Close();  
        return employees; 

        } 

        public CompositeType GetDataUsingDataContract(CompositeType composite) 
        { 
            if (composite == null) 
            { 
                throw new ArgumentNullException("composite"); 
            } 
            if (composite.BoolValue) 
            { 
                composite.StringValue += "Suffix"; 
            } 
            return composite; 
        } 
    } 
} 
于 2012-07-12T20:01:20.077 回答