Silverlight accesses IIS host WCF via httpbinding

Source: Internet
Author: User
Tags serialization silverlight
Silverlight's access to IIS host WCF via httpbiding is the most common and most commonly used in Silverlight and WCF communications, and is demonstrated with a very simple example.
Project structure:
Brief description of Project structure:
Assembly name References that need to be added Brief description
Lxcontracts System.Runtime.Serialization System.ServiceModel For storing operational contracts and data contracts
Lxservices Lxcontracts[Project] Service, implementation of operation contract
Wcfhost.web lxcontracts[projects] and lxservices[projects] Sites that use SVC file Publishing services
Silverlightdemo Silverlight program, calling WCF Service
Note: When you build a Silverlight program, you do not need to host the Web site to create a single Silverlight program, because the Silverlight and WCF services are not placed under the same site to demonstrate cross-domain problems.
Code implementation:
Class Library Lxcontracts: (including data contract Student.cs and operation contract IStudent.cs)
Student.cs Code
   
   
The code is as follows Copy Code
UsingSystem;UsingSystem.Collections.Generic;UsingSystem.Linq;UsingSystem.Text;UsingSystem.ServiceModel;UsingSystem.Runtime.Serialization; Namespacelxcontracts {[DataContract]public classStudent {<summary>///Student Number</summary>[DataMember]public int Stuid {get; set; } <summary>///Student Name</summary>[DataMember]public string Stuname {get; set; } <summary>///Your class</summary>[DataMember]public string ClassName {get; set; } <summary>///Contact Phone</summary>[DataMember]public string Telphonenum {get; set; } } }
Student.cs Code
 
    
    
The code is as follows Copy Code
Using System;
 Using System.Collections.Generic;
 Using system.linq;
 Using system.text;
 Using System.Runtime.Serialization;
 Using system.servicemodel;

 Namespace lxcontracts
{
    [ServiceContract]
    public interface istudent
    {
        [ OperationContract]
        List<Student> getstudent ();
    }
Class Library Lxservices: (class library includes a mock Get database collection class StudentList.cs and service class StudentService.cs)
StudentList.cs
   
   
  code is as follows copy code
Using System;
 Using System.Collections.Generic;
 Using system.linq;
 Using system.text;
 Using lxcontracts;

 Namespace lxservices
{
    public class studentlist:list<student>
    {
         Public studentlist ()
        {
            this. ADD (New Student () {stuid = 1, stuname = "Xiaoming", ClassName = "Computer Class", Telphonenum = "123456" });
             This. ADD (New Student () {stuid = 2, Stuname = "Little Red", ClassName = "Computer class two", Telphonenum = "234567" });
             This. ADD (New Student () {stuid = 2, Stuname = "Xiaolan", ClassName = "Computer class three", Telphonenum = "890123" });
        }
Studentservice Code
   
   
  code is as follows copy code
 using  System;  Using  System.Collections.Generic;  Using  System.Linq; 

Using  System.Text;

 using  lxcontracts;  namespace  lxservices { public class  studentservice:istudent { public List <student>  getstudent () {// The actual situation should be to read from the database //This example manually generate a Student
            List studentlist liststuent = new  studentlist ();
         return  liststuent; }
    }
}
site Wcfhost.web
Site Wcfhost.web, this is a asp.net empty Web application.
1. Right-click "Wcfhost.web"-"Add"-"New Item"-"WCF Service", named "Studentsrv.svc". As shown in figure:
Delete the "StudentSrv.svc.cs" file and the "IStudentSrv.cs" file in the project. Right-click the Studentsrv.svc file, select View markup, and modify the code to:
<%@ ServiceHost language= "C #" service= "Lxservices.studentservice"%>
2, modify the Webconfig file, the code is as follows:
Webconfig
   
   
The code is as follows Copy Code
<?xml version= "1.0" encoding= "Utf-8"?>
<configuration>
  <system.web>
    < Compilation debug= "True" targetframework= "4.0"/>
  </system.web>
  <system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior name= "Lxbehavior" >
          <servicemetadata Httpgetenabled= "true"/>
          <servicedebug includeexceptiondetailinfaults= "false"/>
        </behavior >
      </serviceBehaviors>
    </behaviors>
    <services>
      <service name= " Lxservices.studentservice "behaviorconfiguration=" Lxbehavior ">
        <endpoint address=" "binding=" BasicHttpBinding "contract=" lxcontracts.istudent "/>
      </service>
    </services>
    <!- -Turn off asp.net compatibility mode-->
    <servicehostingenvironment aspnetcompatibilityenabled= "false"/>
  </ System.servicemodel>
</configuration>
Note: The address in endpoint is empty: Because the location of the Svc file is the address of the metadata publication.
3, right click the "studentsrv.svc" file, in the "Browser View", showing the following figure, indicating that the service has been deployed, I use the port is 9090:
To invoke in Silverlight:
Silverlight invocation WCF is simple, adding a "service reference" directly to "Silverlightdemo", and the "servicereferences.clientconfig" configuration file is automatically generated in the Silverlight project. Of course, can also use the way the code calls, but I am lazy:).
1. Add WCF to the Silverlight program:
"Right-click"-"Siverlightdemo"-"Add Service Reference"-"Enter service Address" (mine is http://localhost:9090/WCF/StudentSrv.svc)--click "Go" and you will find a service, Named "WCF." Studentsrv ", click" OK "
2. Invoke WCF in Silverlight:
MainPage.xaml to add the DataGrid control, the XAML code is as follows:
MainPage.xaml Code
   
   
The code is as follows Copy Code
<sdk:datagrid x:name= "dgstudnet" grid.row= "0" autogeneratecolumns= "False" >
            <sdk:DataGrid.Columns>
                <sdk:datagridtextcolumn header= "student number" width= "binding=" {Binding stuid} "/> <sdk:d
                Atagridtextcolumn header= "Student name" width= "binding=" {Binding stuname} "/> <sdk:datagridtextcolumn
                "In class" Width= "binding=" "{Binding ClassName}"/> <sdk:datagridtextcolumn header=
                "phone number" width= "100" binding= "{Binding telphonenum}"/>
            </sdk:DataGrid.Columns>
        </sdk:DataGrid>
MainPage.cs Code
   
   
The code is as follows Copy Code
public partial classMainpage:usercontrol {ObservableCollection<Student>liststudent; PublicMainPage () {InitializeComponent (); Liststudent= new Observablecollection<student>(); This. Loaded + = newRoutedeventhandler (mainpage_loaded); } void Mainpage_loaded (Objectsender, RoutedEventArgs e) {studentclient proxyclient= newstudentclient (); Proxyclient.getstudentasync (); Proxyclient.getstudentcompleted+ + new eventhandler<getstudentcompletedeventargs>(proxyclient_getstudentcompleted); } void Proxyclient_getstudentcompleted (Objectsender, Getstudentcompletedeventargs e) { if (E.error = null) {liststudent=E.result; This.dgStudnet.ItemsSource =liststudent; } } }
Run Result:
Setting "Silverlightdemo" as the startup project, running, produces the following exception:
This is because the project was built at that time without putting the Silverlight program and WCF services on the same site, so you need to place a Cross-domain file in the site root of the release WCF: ClientAccessPolicy.xml
ClientAccessPolicy.xml
<?xml version= "1.0" encoding= "Utf-8"?>
<access-policy>
  <cross-domain-access>
    < policy>
      <allow-from http-request-headers= "SOAPAction" >
        <domain uri= "*"/>
      </ allow-from>
      <grant-to>
        <resource path= "/" include-subpaths= "true"/>
      </grant-to>
    </policy>
  </cross-domain-access>
</access-policy>
Run again, as shown in the following figure:
At this point, Silverlight's demo of WCF accessing the IIS host through httbbingding we'll be here.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.