使用基于WCF REST的服务

时间:2014-05-13 12:34:07

标签: jquery wcf rest

我正在尝试使用JQuery来使用基于REST的WCF服务,但页面上没有任何内容发生。我也尝试过互联网上的各种链接。 请在下面找到我的代码: -

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

<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

<?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>

请告诉我需要在代码中进行哪些更改。 请帮忙 感谢

2 个答案:

答案 0 :(得分:1)

对于WebGet,您需要以字符串格式提供所有参数。

  [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; 
    }

您还可以包含WCF跟踪以跟踪任何与调度相关的日志。 打开WCF跟踪以获取日志。

    <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>

<强>更新

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);
            }
        });
    }

答案 1 :(得分:0)

尝试在javascript的ajax代码中更新以下行

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

即。 'id'在方法

的参数中是小写的

修改

尝试导航服务网址

我认为这可能不可用,端口是否可用(即开发Web服务器?)?