質問

I am trying to consume my REST based WCF service using JQuery, but nothing is happening on Page. I have also tried various links on the internet. Please find my code below:-

IService1.cs

namespace WcfRest
{

[ServiceContract]

public interface IService1
{

    [WebGet(ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped, UriTemplate = "Employee?id={id}")]
    [OperationContract]
    List<Employee> GetEmployeeDetails(int Id);
 }

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

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

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

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

}
}

Service1.svc.cs

namespace WcfRest
{
 [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class Service1 : IService1
{
    SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=Test;User ID=sa;Password=sa");

    public List<Employee> GetEmployeeDetails(int Id)
    {
        Employee emp = new Employee();
        con.Open();
        SqlCommand cmd = new SqlCommand("Select Id,sEmpName,iSalary,sDept from Emp where Id='" + Id + "' ", con);
        SqlDataReader dr;
        dr = cmd.ExecuteReader();
        dr.Read();
        emp.EmpId = Convert.ToInt32(dr["Id"]);
        emp.EmpName = dr["sEmpName"].ToString();
        emp.Salary = Convert.ToInt32(dr["iSalary"]);
        emp.Dept = dr["sDept"].ToString();
        con.Close();
        List<Employee> list = new List<Employee>();
        list.Add(emp);
        return list; 
    }
 }
}

web.config of service

<configuration>

<system.web>
    <compilation debug="true" targetFramework="4.0" />
</system.web>
<system.serviceModel>

    <behaviors>
        <serviceBehaviors>
            <behavior name="ServiceBehaviour">
                <!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
                <serviceMetadata httpGetEnabled="true"/>
                <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
                <serviceDebug includeExceptionDetailInFaults="true"/>
            </behavior>
        </serviceBehaviors>
        <endpointBehaviors>
            <behavior name="web">
                <webHttp/>
            </behavior>
        </endpointBehaviors>
    </behaviors>
    <services>
        <service name="WcfRest.Service1" behaviorConfiguration="ServiceBehaviour">
            <endpoint address="" binding="webHttpBinding" contract="WcfRest.IService1" behaviorConfiguration="web">
            </endpoint>
        </service>
    </services>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
    <standardEndpoints>
        <webScriptEndpoint>
            <standardEndpoint  crossDomainScriptAccessEnabled="true" name=""/>
        </webScriptEndpoint>
    </standardEndpoints>

    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
</system.serviceModel>

ConsumeService.aspx

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
 <div>
   <script type="text/javascript">
        $(function () {
    $('#btn1').click(getEmployeeWCF);
});
    function getEmployeeWCF() {
        $.ajax({
            type: "POST",
            url: "http://localhost:1626/Service1.svc/GetEmployeeDetails",
            //data: "{}",
            data: "{'Id':'" + $('#txt1').val() + "'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (response) {
                var employee = response.d;
                $('#output').empty();
                $.each(employee, function (index, emp) {
                    $('#output').append('<p></strong><br /> Id: ' +
                                            emp.Id + '<br />Name: ' +
                                            emp.Name + '<br />Salary: £' +
                                            emp.Salary + '<br />Department: ' +
                                            emp.Department + '</p>');
                });

            },
            failure: function (msg) {
                $('#output').text(msg);
            }
        });
    }

</script>


    <asp:TextBox ID="txt1" runat="server"></asp:TextBox>


    <input id="btn1" type="button" value="button" /></div>
</form>

web.config of website

<?xml version="1.0"?>

<configuration>
    <system.web>
        <compilation debug="true" targetFramework="4.0">
            <assemblies>
                <add assembly="mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/></assemblies></compilation>
    </system.web>
</configuration>

Please tell what changes I need to make in my code. Please Help Thanks

役に立ちましたか?

解決

In case of WebGet you need to provide all parameter in string format.

  [Serializable]   //Added this new attribute
  [DataContract]
    public class Employee
    {
        [DataMember]
        public int EmpId { get; set; }

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

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

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

}
public interface IService1
{

    [WebGet(ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped, UriTemplate = "Employee?id={id}")]
    [OperationContract]
    List<Employee> GetEmployeeDetails(**string Id**);   //Changed int id to string id
 }


public List<Employee> GetEmployeeDetails(**string Id**)  //Changed int id to string id
    {
        Employee emp = new Employee();
        con.Open();
        SqlCommand cmd = new SqlCommand("Select Id,sEmpName,iSalary,sDept from Emp where Id='" + Id + "' ", con);
        SqlDataReader dr;
        dr = cmd.ExecuteReader();
        dr.Read();
        emp.EmpId = Convert.ToInt32(dr["Id"]);
        emp.EmpName = dr["sEmpName"].ToString();
        emp.Salary = Convert.ToInt32(dr["iSalary"]);
        emp.Dept = dr["sDept"].ToString();
        con.Close();
        List<Employee> list = new List<Employee>();
        list.Add(emp);
        return list; 
    }

You can also include WCF Trace for tracing any dispatch related logs. Open the WCF trace for getting logs.

    <configuration>
       <system.diagnostics>
            <trace autoflush="true" />
            <sources>
                <source name="System.ServiceModel" switchValue="Information, ActivityTracing" propagateActivity="true">
                    <listeners>
                        <add name="wcfTraceListener" type="System.Diagnostics.XmlWriterTraceListener" initializeData="G:\Errors\WcfTrace.svclog" traceOutputOptions="DateTime" />
                    </listeners>
                </source>
            </sources>
        </system.diagnostics>
</configuration>

UPDATE

function getEmployeeWCF() {
        $.ajax({
            type: "GET",
            url: "http://localhost:1626/Service1.svc/GetEmployeeDetails?id=" + $('#txt1').val() ,

            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (response) {
                var employee = response.d;
                $('#output').empty();
                $.each(employee, function (index, emp) {
                    $('#output').append('<p></strong><br /> Id: ' +
                                            emp.Id + '<br />Name: ' +
                                            emp.Name + '<br />Salary: £' +
                                            emp.Salary + '<br />Department: ' +
                                            emp.Department + '</p>');
                });

            },
            failure: function (msg) {
                $('#output').text(msg);
            }
        });
    }

他のヒント

Try updating below line in ajax code of javascript

data: "{'id':'" + $('#txt1').val() + "'}",

ie. 'id' is in lowercase in argument of method

EDIT

Try to navigate service URL

I think this might not be available, is the port avaialble (i.e. development web server?)?

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top