Here I will explain how to use or consume WCF (windows communication foundation) service in web application using asp.net.
Description:
Column Name | Data Type | Allow Nulls |
UserId | Int(Set Identity=true) | No |
UserName | nvarchar(MAX) | Yes |
FirstName | varchar(50) | Yes |
LastName | varchar(50) | Yes |
Location | varchar(50) | Yes |
![]() |
![]() |
using System.Collections.Generic; using System.Runtime.Serialization; using System.ServiceModel; |
[ServiceContract] public interface IService { [OperationContract] List<UserDetails> GetUserDetails(string Username); [OperationContract] string InsertUserDetails(UserDetails userInfo); } // Use a data contract as illustrated in the sample below to add composite types to service operations. [DataContract] public class UserDetails { string username = string.Empty; string firstname = string.Empty; string lastname = string.Empty; string location = string.Empty; [DataMember] public string UserName { get { return username; } set { username = value; } } [DataMember] public string FirstName { get { return firstname; } set { firstname = value; } } [DataMember] public string LastName { get { return lastname; } set { lastname = value; } } [DataMember] public string Location { get { return location; } set { location = value; } } } |
using System.Collections.Generic; using System.Configuration; using System.Data; using System.Data.SqlClient; |
public class Service : IService { private string strConnection = ConfigurationManager.ConnectionStrings["dbconnection"].ToString(); public List<UserDetails> GetUserDetails(string Username) { List<UserDetails> userdetails = new List<UserDetails>(); using (SqlConnection con=new SqlConnection(strConnection)) { con.Open(); SqlCommand cmd = new SqlCommand("select * from UserInformation where UserName Like '%'+@Name+'%'", con); cmd.Parameters.AddWithValue("@Name", Username); SqlDataAdapter da = new SqlDataAdapter(cmd); DataTable dtresult = new DataTable(); da.Fill(dtresult); if(dtresult.Rows.Count>0) { for(int i=0;i<dtresult.Rows.Count;i++) { UserDetails userInfo = new UserDetails(); userInfo.UserName = dtresult.Rows[i]["UserName"].ToString(); userInfo.FirstName = dtresult.Rows[i]["FirstName"].ToString(); userInfo.LastName = dtresult.Rows[i]["LastName"].ToString(); userInfo.Location = dtresult.Rows[i]["Location"].ToString(); userdetails.Add(userInfo); } } con.Close(); } return userdetails; } public string InsertUserDetails(UserDetails userInfo) { string strMessage = string.Empty; using (SqlConnection con=new SqlConnection(strConnection)) { con.Open(); SqlCommand cmd = new SqlCommand("insert into UserInformation(UserName,FirstName,LastName,Location) values(@Name,@FName,@LName,@Location)", con); cmd.Parameters.AddWithValue("@Name", userInfo.UserName); cmd.Parameters.AddWithValue("@FName", userInfo.FirstName); cmd.Parameters.AddWithValue("@LName", userInfo.LastName); cmd.Parameters.AddWithValue("@Location", userInfo.Location); int result= cmd.ExecuteNonQuery(); if(result==1) { strMessage = userInfo.UserName+ " Details inserted successfully"; } else { strMessage = userInfo.UserName + " Details not inserted successfully"; } con.Close(); } return strMessage; } } |
<connectionStrings> <add name="dbconnection" connectionString="Data Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB"/> </connectionStrings> |
Create new website from visual studio select New---> Website and give some name as you like.
![]() |
![]() |
![]() |
<html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Untitled Page</title> <style type="text/css"> .style1 { height: 26px; } </style> </head> <body> <form id="form1" runat="server"> <div> <table align="center"> <tr> <td colspan="2" align="center"> <b>User Registration</b> </td> </tr> <tr> <td> UserName: </td> <td> <asp:TextBox ID="txtUserName" runat="server"/> </td> </tr> <tr> <td> FirstName: </td> <td> <asp:TextBox ID="txtfname" runat="server"/> </td> </tr> <tr> <td> LastName: </td> <td> <asp:TextBox ID="txtlname" runat="server"/> </td> </tr> <tr> <td class="style1"> Location: </td> <td class="style1"> <asp:TextBox ID="txtlocation" runat="server"/> </td> </tr> <tr> <td> </td> <td> <asp:Button ID="btnSubmit" runat="server" Text="Submit" onclick="btnSubmit_Click" /> </td> </tr> <tr> <td colspan="2"> <asp:Label ID="lblResult" runat="server"/> </td> </tr> <tr> <td colspan="2"> <asp:GridView runat="server" ID="gvDetails" AutoGenerateColumns="false"> <RowStyle BackColor="#EFF3FB" /> <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" /> <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" /> <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" /> <AlternatingRowStyle BackColor="White" /> <Columns> <asp:BoundField HeaderText="UserName" DataField="UserName" /> <asp:BoundField HeaderText="FirstName" DataField="FirstName" /> <asp:BoundField HeaderText="LastName" DataField="LastName" /> <asp:BoundField HeaderText="Location" DataField="Location" /> </Columns> </asp:GridView> </td> </tr> </table> </div> </form> </body> </html> |
using System; using System.Collections.Generic; using ServiceReference1; |
ServiceReference1.ServiceClient objService = new ServiceClient(); protected void Page_Load(object sender, EventArgs e) { if(!IsPostBack) { BindUserDetails(); } } protected void BindUserDetails() { IList<UserDetails> objUserDetails = new List<UserDetails>(); objUserDetails = objService.GetUserDetails(""); gvDetails.DataSource = objUserDetails; gvDetails.DataBind(); } protected void btnSubmit_Click(object sender, EventArgs e) { UserDetails userInfo = new UserDetails(); userInfo.UserName = txtUserName.Text; userInfo.FirstName = txtfname.Text; userInfo.LastName = txtlname.Text; userInfo.Location = txtlocation.Text; string result= objService.InsertUserDetails(userInfo); lblResult.Text = result; BindUserDetails(); txtUserName.Text = string.Empty; txtfname.Text = string.Empty; txtlname.Text = string.Empty; txtlocation.Text = string.Empty; } |
<endpoint address=" http://localhost/WCFServiceSample/Service.svc" binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_IService" contract="ServiceReference1.IService" name="WSHttpBinding_IService"> <identity> <dns value="localhost" /> </identity> </endpoint> |
|
If you enjoyed this post, please support the blog below. It's FREE! Get the latest Asp.net, C#.net, VB.NET, jQuery, Plugins & Code Snippets for FREE by subscribing to our Facebook, Twitter, RSS feed, or by email. |
|||
Subscribe by RSS
Subscribe by Email
|
|||
|
|
|







Subscribe by RSS
Subscribe by Email
45 comments :
great example dude
great work .. keep going ....
Hi Suresh,
Nice Work.. However, i am unable to consume WCF Service in my application. Its giving me following error,
he HTTP request is unauthorized with client authentication scheme 'Negotiate'. The authentication header received from the server was 'Negotiate,NTLM'.
Can u pls tell solution on this ?
Regards,
Rohit Pundlik
Very nice indeed..... keep it up !!!!!!
very nice example...after abt 1 hour googling i got this example...
http://aspdotnetcode.blogspot.com/
Suresh your blog seems extremly awsome,but could you please tell me when u are coming with MVC in your blog with your teaching style?
Hi Suresh,
IList userdetails = new List();
userdetails = objService.GetUserDetails("as");
In that following code objService.GetUserDetails("as");
is throwing some error like "Can't implicit convert type..."
Can you give me solution please...
Hi Suresh,
IList userdetails = new List();
userdetails = objService.GetUserDetails("as");
In that following code objService.GetUserDetails("as");
is throwing some error like "Can't implicit convert type..."
Can you give me solution please...
Good job bro
Simerdeep Singh from Canada
www.cosmicdatainc.com
this is a very useful example sir.....but m beginner of mvc application..so can u pls tell me how to consume this same wcf service using an mvc applicaion..?
Perfect!!!! Point to point
very good example
very good example
HI suresh
the code is giving error objService.GetUserDetails("as");
is throwing some error like "Can't implicit convert type..."
thank you so much your collection is really helpfull
Thank u so much for kind inf..abt the WCF..its help me a lot ........
Nice work... keep up the good work
Very good example. Thank you Suresh
Greate,Tell me UPDATE,DELETE also pls
hi suresh,
is apply css in window application using C#
Great work
very good example. can i know how can we consume a WCF Service in MVC 3 Application?
http:\\yahoo.com
good one very useful information...
very good
Lovely...Thanks...
hi suresh sir
while doing this im getting this error
Plz help me to solve this error
The server was unable to process the request due to an internal error. For more information about the error, either turn on IncludeExceptionDetailInFaults (either from ServiceBehaviorAttribute or from the configuration behavior) on the server in order to send the exception information back to the client, or turn on tracing as per the Microsoft .NET Framework 3.0 SDK documentation and inspect the server trace logs.
Hi,
Thanks for making us understand WCF clearly with examples
Am getting below error
plz helpme out
The server was unable to process the request due to an internal error. For more information about the error, either turn on IncludeExceptionDetailInFaults (either from ServiceBehaviorAttribute or from the configuration behavior) on the server in order to send the exception information back to the client, or turn on tracing as per the Microsoft .NET Framework 3.0 SDK documentation and inspect the server trace logs.
Thanks
Archana
Nice article .Will you pls explain how to make MVC 4 ?
when i type h in text box in location field i need to get all the values starting with 'h' in database as shown above..evrything is working fine except that i am not getting that
Thanks a lot for wonderful example
hi suresh sir
nice example
but when i am trying to insert
time out error given.
sir please tell me the solution for this.
thanks
Vinayak
thanks a lot for great example.
hi suresh
thnx for the post,if you will post some REAL TIME scene with code than WCF will be more easy to understand so plz ost some real time scene on wcf
thanks yaar..
Your Explanation simply nice...
Hi suresh
I used the same example.i am getting this error
" The Address property on ChannelFactory.Endpoint was null. The ChannelFactory's Endpoint must have a valid Address specified."
is throwing some error like "Can't implicit convert type..."
Good Explanation
hey i tried this with vs2010,but i couldnt host it in IIS, can you explain me how to deploy this WCF service in IIS. your link abo ut deploy only deals with website not WCF deployment
can you provide with details how to deploy it in IIS , i am using VS2010.I need this example in VS2010 with creation and deployment. Thanks
Sathish - Very sueful
very great articles posted by you...
Hi
i am getting error while accessing your application as
The HTTP service located at
http://localhost/sampleuserservice/Service.svc is too busy.
can you provide me some solution