【问题标题】:Bind data to grid by using GET in WCF method data is not binding在 WCF 方法中使用 GET 将数据绑定到网格数据未绑定
【发布时间】:2018-01-12 13:18:28
【问题描述】:

通过使用 WCF post 方法,我将数据存储在数据库中,然后我希望使用 WCF GET 将存储的数据显示在网格控件中。在这里,我编写了代码以使用 POST 方法将数据存储在数据库中。这是工作。将存储的数据绑定到网格控件时出现错误。

我得到以下错误:

在 ServiceModel 客户端配置部分中找不到引用合同“ServiceReference1.IService2”的默认端点元素。这可能是因为找不到您的应用程序的配置文件,或者因为在客户端元素中找不到与此协定匹配的端点元素。

//service.cs

[ServiceContract]
public interface IService1
{
    [OperationContract()]
    void AddStudent(StudentDetails sd);
}

[ServiceContract]
public interface IService2
{
    [OperationContract]
    Employee GetEmployee();
}

//service.svc

public class Service1 : IService1, IService2
{

    [WebInvoke(UriTemplate = "ADDStudent", Method = "POST", ResponseFormat = WebMessageFormat.Json)]
    public void AddStudent(StudentDetails sd)
    {
        string constr = ConfigurationManager.ConnectionStrings["mine"].ConnectionString;
        SqlConnection con = new SqlConnection(constr);
        SqlCommand cmd = new SqlCommand("insert into students values (@Studentname,@SDepartment,@SAddress,@SMobile)", con);
        con.Open();
        cmd.Parameters.AddWithValue("@Studentname", sd.StudentName);
        cmd.Parameters.AddWithValue("@SDepartment", sd.SDepartment);
        cmd.Parameters.AddWithValue("@SAddress", sd.SAddress);
        cmd.Parameters.AddWithValue("@SMobile", sd.SMobile);
        cmd.ExecuteNonQuery();
        con.Close();
    }

    [WebGet(UriTemplate = "Empdetails", ResponseFormat = WebMessageFormat.Json)]
    public Employee GetEmployee()
    {

        Employee emp = new Employee();
        string constr = ConfigurationManager.ConnectionStrings["mine"].ConnectionString;
        SqlConnection con = new SqlConnection(constr);
        //write code to bind data to a grid con5trol.
        SqlCommand cmd = new SqlCommand("select * from students", con);
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataTable st = new DataTable();
        da.Fill(st);
        emp.EmployeeTable = st;
        return emp;


    }

}

[DataContract()]
public class StudentDetails
{
    [DataMember(Order = 0)]
    public string StudentName { get; set; }
    [DataMember(Order = 1)]
    public string SDepartment { get; set; }
    [DataMember(Order = 2)]
    public string SAddress { get; set; }
    [DataMember(Order = 3)]
    public string SMobile { get; set; }
}

[DataContract]
public class Employee
{
    [DataMember]
    public DataTable EmployeeTable {  get; set;  }
}

//web.config 文件

 <?xml version="1.0"?>
 <configuration>
  <connectionStrings>
          <add name="mine" connectionString="Data Source=
          (localdb)\v11.0;Initial Catalog=yash;Integrated Security=true"/>
          </connectionStrings>
        <appSettings>
       <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" 
           />       
         </appSettings>
                  <system.web>
                 <compilation debug="true" targetFramework="4.5" />
              <httpRuntime targetFramework="4.5"/>
           </system.web>
              <system.serviceModel>

          <services> <!--1-->
               <service behaviorConfiguration="ServiceBehaviour" 
                 name="CreateService.Service1">

                   <endpoint behaviorConfiguration="Service1"  address="" 
      binding="webHttpBinding" bindingConfiguration="" 
          contract="CreateService.IService1">
       </endpoint>

        <endpoint behaviorConfiguration="Service1"  address=""
     binding="webHttpBinding" bindingConfiguration="" 
    contract="CreateService.IService2">
     </endpoint>




  </service>
</services>

           <behaviors> <!--2-->
  <serviceBehaviors>
    <behavior name="ServiceBehaviour">
      <serviceMetadata httpGetEnabled="true"/>

      <serviceDebug includeExceptionDetailInFaults="false"/>
    </behavior>
   </serviceBehaviors>
         <endpointBehaviors>
    <behavior name="Service1">
      <webHttp/>
    </behavior>
  </endpointBehaviors>
          </behaviors>

       <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
   </system.serviceModel>
       <system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
       </system.webServer>

        </configuration>

////////////wcf 消耗量////////

using System;
            using System.Collections.Generic;
         using System.Linq;
          using System.Web;
            using System.Web.UI;
              using System.Web.UI.WebControls;
                using System.ServiceModel;
           using System.ServiceModel.Channels;
            using System.Runtime.Serialization;
          using System.Web.Script.Serialization;
      using System.Runtime.Serialization.Json;
           using System.IO;
          using System.Net;
   using System.Data;
        using System.Data.SqlClient;
        using System.Text;
           using ConsumptionWcf.ServiceReference1;
        namespace ConsumptionWcf
           {
         public partial class WebForm1 : System.Web.UI.Page
            {
    public class StudentDetails
              {
        public string StudentName { get; set; }
        public string SDepartment { get; set; }
        public string SAddress { get; set; }
        public string SMobile { get; set; }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        //Service1Employee semp = new Service1Employee();
        Service2Client myservice = new Service2Client();
        Employee emp = new Employee();
        emp = myservice.GetEmployee();
        DataTable dt = new DataTable();
        dt = emp.EmployeeTable;
        grid1.DataSource = dt;
        grid1.DataBind();

    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        StudentDetails stu = new StudentDetails
        {
           // StudentName = TextBox1.Text,
            //  StudentName = Request["TextBox1"],
            //StudentName = Request.Params["TextBox1"],
            StudentName = Request.Form["TextBox1"],//Request Is Propery Of 
    Request Collections,Request Collection Object Is HttpRequest. 
             //Above Four Are The Methods To Collect Data At The Server 
         Side.

            //SAddress = TextBox2.Text,
            //SAddress = Request["TextBox2"],
            //SAddress =  Request.Params["TextBox2"],
            SAddress = Request.Form["TextBox2"],

            //SMobile = TextBox3.Text,
            //SMobile = Request["TextBox3"],
            //SMobile = Request.Params["TextBox3"],
            SMobile = Request.Form["TextBox3"],

            //SDepartment = TextBox4.Text
            //    SDepartment = Request["TextBox4"]
             //SDepartment = Request.Params["TextBox4"]
            SDepartment = Request.Form["TextBox4"]

        };
        DataContractJsonSerializer objseria = new 
                DataContractJsonSerializer(typeof(StudentDetails));
        MemoryStream mem = new MemoryStream();
        objseria.WriteObject(mem, stu);
        string data = Encoding.UTF8.GetString(mem.ToArray(), 0, 
    (int)mem.Length);
        WebClient webClient = new WebClient();
        webClient.Headers["Content-type"] = "application/json";
        webClient.Encoding = Encoding.UTF8;


  webClient.UploadString("http://localhost:58369/Service1.svc/ADDStudent", 
              "POST", data);

        Label1.Text = "Details saved using Rest service";
        Response.Redirect("WebForm1.aspx");



        DataContractJsonSerializer objseria1 = new 
        DataContractJsonSerializer(typeof(StudentDetails));
        MemoryStream mem1 = new MemoryStream();
        objseria.WriteObject(mem, stu);
        string data1 = Encoding.UTF8.GetString(mem.ToArray(), 0, 
         (int)mem.Length);
        WebClient webClient1 = new WebClient();
        webClient.Headers["Content-type"] = "application/json";
        webClient.Encoding = Encoding.UTF8;
    webClient.UploadString("http://localhost:58369/Service1.svc/Empdetails", 
    "GET", data);

    }
       }

【问题讨论】:

  • 请不要在此处发布您的整个程序。隔离不起作用的代码。这个问题,它的发布方式,属于“为什么这个代码不起作用”。不要指望有人会在你留下的占位符中编码和发布代码

标签: c# asp.net .net wcf


【解决方案1】:

我看到你的 service.cs 是下面代码的命名空间

     namespace service
   {
        public class Service1 : IService1, IService2
        {

        [WebInvoke(UriTemplate = "ADDStudent", Method = "POST", ResponseFormat = WebMessageFormat.Json)]
        public void AddStudent(StudentDetails sd)
        {
            string constr = ConfigurationManager.ConnectionStrings["mine"].ConnectionString;
            SqlConnection con = new SqlConnection(constr);
           //rest of the code
        }
}

但是您描述配置的 web.config 文件具有不同的名称,因此会引发端点未定义的异常,服务的名称必须是命名空间,后跟实现服务合同类型的类。以下是修改后的代码。

//web.config 文件

     <services> <!--1 name =Namespace.ImplementingClass-->
                           <service behaviorConfiguration="ServiceBehaviour" 
                             name="service.Service1">

         <endpoint behaviorConfiguration="Service1"  address="" 
          binding="webHttpBinding" bindingConfiguration="" 
              contract="CreateService.IService1">
           </endpoint>

【讨论】:

  • 谢谢,这里你为一个端点写了代码,如何为另一个端点写配置。
  • @lavangoud ,您可以在 web.config 文件中添加任意数量的端点,我只使用了一个端点来编写最少的代码。
猜你喜欢
  • 1970-01-01
  • 2016-11-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-28
  • 1970-01-01
  • 2012-12-25
  • 2013-03-23
相关资源
最近更新 更多