从Jquery调用WCF Restful Services

时间:2014-12-15 18:18:50

标签: c# jquery asp.net asp.net-mvc wcf

我已经创建了WCF Restfull服务,但是当我从JS调用它时,它总是说没有找到Respurce。 这是员工类

namespace WcfRestMVC.Models
{
    [DataContract]
    public class Employee
    {
        [Key]
        [DataMember]
        public int Id { get; set; }
        [DataMember]
        public string FirstName { get; set; }
        [DataMember]
        public string LastName { get; set; }

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

serviceInterface等

namespace WcfRestMVC
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IEmployeeService" in both code and config file together.
    [ServiceContract]
    public interface IEmployeeService
    {
        [OperationContract]
        [WebGet(UriTemplate = "Employees", ResponseFormat = WebMessageFormat.Json)]
        Employee[] GetAllEmployee();

        [OperationContract]
        [WebGet(UriTemplate = "EmployeeById/{id}", ResponseFormat = WebMessageFormat.Json)]
        Employee GetEmployeeByID(string Id);
    }
}

我的服务

namespace WcfRestMVC
{
    public class EmployeeService : IEmployeeService
    {
        public Employee[] GetAllEmployee()
        {
            using (DemoContext Dbobj = new DemoContext())
            {
                var getAllEmployee = Dbobj.eployees.ToList();
                return getAllEmployee.ToArray();
            }
        }


        public Employee GetEmployeeByID(string Id)
        {
            using (DemoContext Dbobj = new DemoContext())
            {
                var GetEmployeeById = Dbobj.eployees.FirstOrDefault(m => m.Id == Convert.ToInt32(Id));
                return GetEmployeeById;
            }
        }
    }
}

我的web.config文件为

<system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
          <serviceDebug includeExceptionDetailInFaults="false"/>
        </behavior>
      </serviceBehaviors>
      <endpointBehaviors>
        <behavior name="webBehavior">
          <webHttp />
        </behavior>
      </endpointBehaviors>
    </behaviors>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
    <services>
      <service name="WcfRestMVC.EmployeeService">
        <endpoint address="" behaviorConfiguration="webBehavior" binding="webHttpBinding" contract="WcfRestMVC.IEmployeeService" />
      </service>
    </services>
  </system.serviceModel>

我是从JS <​​/ p>调用它

$.ajax({
        type: "GET",
        url: "http://localhost:61716/EmployeeService.svc/Employees",
        contentType: "json",
        dataType: "json",
        success: function (data) {
            var d = data;
        },
        error: function (xhr) {
        var s=xhr;
        }
    });

也可以在我的浏览器中粘贴此网址

http://localhost:61716/EmployeeService.svc/Employees

它说无法找到资源。。 我认为我的web.config文件有问题。你能帮我吗?

1 个答案:

答案 0 :(得分:0)