简体   繁体   English

在WCF方法中使用GET将数据绑定到网格的数据未绑定

[英]Bind data to grid by using GET in WCF method data is not binding

By using WCF post method, I stored data in database, then I want stored data display in grid control by using WCF GET. 通过使用WCF发布方法,我将数据存储在数据库中,然后希望使用WCF GET在网格控件中显示存储的数据。 Here I wrote code to store data in database using POST method. 在这里,我编写了使用POST方法将数据存储在数据库中的代码。 It is working. 这是工作。 I get error while binding stored data to grid control. 将存储的数据绑定到网格控件时出现错误。

The below error I get: 我得到以下错误:

Could not find default endpoint element that references contract 'ServiceReference1.IService2' in the ServiceModel client configuration section. 在ServiceModel客户端配置部分中找不到引用合同'ServiceReference1.IService2'的默认终结点元素。 This might be because no configuration file was found for your application, or because no endpoint element matching this contract could be found in the client element. 这可能是因为找不到您的应用程序的配置文件,或者是因为在客户端元素中找不到与该协定匹配的端点元素。

//service.cs //service.cs

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

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

//service.svc //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 file //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 consumption//////// ////////////// 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);

    }
       }

As I see your service.cs is the namespace for below code 如我所见,您的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
        }
}

But your web.config file which describes the configuration has different name and hence endpoint not defined exception is thrown,the name of the service must be the namespace followed by the class that is implementing the service contract types .Below is the modified code. 但是您的描述配置的web.config文件具有不同的名称,因此会引发未定义的端点异常,服务的名称必须是名称空间,后跟实现服务协定类型的类。下面是修改后的代码。

//web.config file //web.config文件

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM