Call WCF Rest Service without svc file and wcf configuration

來源:互聯網
上載者:User

1. Create Empty Web Project and add the following class along with its associated interface code

public class Person
    {
        public string Id
        {
            get;
            set;
        }

        public string Name
        {
            get;
            set;
        }
    }

    [ServiceContract]
    interface IPersonService
    {

        [OperationContract]
        Person GetPO();

        [OperationContract]
         string SayHello(string name);

        [OperationContract]
        Person GetPerson(string id);  

 

        [OperationContract] 
        Person InsertPerson(Person person); 
       
        [OperationContract]
        Person UpdatePerson(string id, Person person); 
       
        [OperationContract]
        void DeletePerson(string id);

        [OperationContract]
        string SE();

        [OperationContract]
        Stream Post(string message, int x, int y);
    }

 

 

[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class PersonService : IPersonService
    {
        public List<Person> PersonList= new List<Person>();

         [WebGet(UriTemplate = "SE")]
         public string SE()
    {
      return "this is test";
    }

         [WebGet(UriTemplate = "ss")]
         public Person GetPO()
         {
             Person p = new Person();
             p.Id = "testid";
             p.Name = "personname";
             return p;
         }

         [WebGet(UriTemplate = "SayHello({name})")]
public string SayHello(string name)
    {

        return string.Format("Hello, {0}" , name);

    }

        [WebGet(UriTemplate = "Person({id})")]
        public Person GetPerson(string id)
        {
            Person p = new Person();
            p.Id = id;
            p.Name = "person name";
            return p;
        }  

   

        [WebInvoke(UriTemplate = "Ins", Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]

        public Person InsertPerson(Person person) 
        {

            Person p = person;
            p.Id = "changedid";
            return p;
       
        } 
       
        [WebInvoke(UriTemplate = "Person({id})", Method = "PUT")] 
        public Person UpdatePerson(string id, Person person) 
        {
            var a = from p in ps
                    where p.Id == id
                    select p;
            return a as  Person;

        } 
       
        [WebInvoke(UriTemplate = "Person({id})", Method = "DELETE")] 
        public void DeletePerson(string id)
        {
            ps.RemoveAt(int.Parse(id));

        }

        [WebInvoke(BodyStyle = WebMessageBodyStyle.Wrapped, RequestFormat = WebMessageFormat.Json, UriTemplate="")]
        public Stream Post(string message, int x, int y) { return new MemoryStream(Encoding.UTF8.GetBytes("<b>" + message + (x + y) + "</b>")); }
   
    }

 

Web.config :

<configuration>
    <system.web>
        <compilation debug="true" targetFramework="4.0" />
    </system.web>
  <system.serviceModel>
     <serviceHostingEnvironment aspNetCompatibilityEnabled="true" minFreeMemoryPercentageToActivateService="1"/>
    <standardEndpoints>
           <webHttpEndpoint>
           <standardEndpoint name="" helpEnabled="true" automaticFormatSelectionEnabled="true"/>  

      </webHttpEndpoint>  
    </standardEndpoints>

   
  </system.serviceModel>
</configuration>

 

minFreeMemoryPercentageToActivateService attribute is needed only when the red memory error occurs.

 

HTML Page:

function getPerson() {

            var name = $("#name").val();
            $.ajax({
                cache: false,
                type: "GET",
                async: false,
                url: "Person"+ "(" + name +")",
                dataType: "json",

                processData: false,

                success: function (msg) {

                    alert(msg.Name);

                },

                error: function (err) {

                    //error handling

                    alert("Error Occured!" + err.msg);

                }

            });

        }

 

 function postdata() {
            alert("begin");
            $.ajax({  url: "/",
                      type: "POST",
                      contentType: "application/json",
                      data: '{"x":"1","y":"2","message":"The answer is: "}',
                      dataType: "html",
                      success: function (data) { $('body').html(data); },
                      error: function (err) { alert("Error Occured!" + err.msg);}

                  });
              }

              function InsertPeople() {
                  //調用方法並傳遞一個json格式的Person對象,返回結果是一個json格式對象
                  var data = { Name: "Denny", Id: "23" };
                  var jsonStr = JSON.stringify(data); //將對象格式化成json字串
                  sendAJAX("Ins", jsonStr,
                   function (msg) {                                
                       alert(msg.Name + "   " + msg.Id + " this is a test case");
                });
           }
             

              function sendAJAX(url, data, success) {
                  $.ajax({
                      type: "POST",
                      contentType: "application/json",
                      url: url,
                      data: data,
                      processData: false,
                      success: success,
                      error: function (XMLHttpRequest, textStatus, errorThrown) {
                          alert("Error Occured!");
                      }
                  });
              }

 

The code above is the demo code for calling wcf rest service without svc file using jquery, hopefully it's a basic guideline for all of you:)

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.