RESTfulサービスの構築

24816 ワード

1.設計上の注意事項
  • どのようなリソースが必要ですか?
  • は、これらのリソースを表すURIを使用しますか?
  • 各URIは、統合インターフェースのどの部品(HTTP動詞)
  • を支援するか.
    2.次の設計uri
    3.wcfエンジニアリングStudioサービスを構築し、裏面のすべてのコードを削除する
    3.1使用されるクラスをいくつか作成する
        public class IssuesCollection
    
        {
    
            public string SchoolName { get; set; }
    
            public List<IssuesData> IssuesDatas;
    
        }
        public class IssuesData
    
        {
    
            public string Issues { set; get; }
    
    
    
            public int Year { set; get; }
    
        }



    View Code
        public class Student
    
        {
    
            public int ID { get; set; }
    
            public string Name { get; set; }
    
            public Nullable<int> Score { get; set; }
    
            public string State { get; set; }
    
        }
    
    
    
        public class Department
    
        {
    
            public string SchoolName { get; set; }
    
            public string DepartmentName { get; set; }
    
            public List<Student> Students { get; set; }
    
        }

    3.2サービスクラスの確立、主な処理クラス


    View Code
        [ServiceContract]
    
        [AspNetCompatibilityRequirements(RequirementsMode
    
            = AspNetCompatibilityRequirementsMode.Allowed)]
    
        public class Service
    
        {
    
            [OperationContract]
    
            [WebGet(UriTemplate = "/")]
    
            public IssuesCollection GetAllIssues()
    
            {
    
                //Iniissues();
    
                //return issues;
    
                IssuesCollection issues1 = new IssuesCollection();
    
                issues1.SchoolName = "gsw";
    
                issues1.IssuesDatas = new List<IssuesData>();
    
                for (int i = 0; i < 10; i++)
    
                {
    
                    IssuesData item = new IssuesData() { Issues = "gsw" + i.ToString(), Year = 2010 + i };
    
                    issues1.IssuesDatas.Add(item);
    
                }
    
                return issues1;
    
            }
    
    
    
            [OperationContract]
    
            [WebGet(UriTemplate = "Service/GetDepartment")]
    
            public Department GetDepartment()
    
            {
    
                Department department = new Department
    
                {
    
                    SchoolName = "    ",
    
                    DepartmentName = "   ",
    
                    Students = new List<Student>()
    
                };
    
    
    
                return department;
    
            }
    
    
    
            [OperationContract]
    
            [WebGet(UriTemplate = "Service/GetAStudent({id})")]
    
            public Student GetAStudent(string id)
    
            {
    
                Random rd = new Random();
    
                Student aStudent = new Student
    
                    {
    
                        ID = System.Convert.ToInt16(id), 
    
                        Name = "Name No. " + id,
    
                        Score = Convert.ToInt16(60 + rd.NextDouble() * 40),
    
                        State = "GA"
    
                    };
    
    
    
                return aStudent;
    
            }
    
    
    
            [OperationContract]
    
            [WebInvoke(Method ="POST", UriTemplate = "Service/AddStudentToDepartment",
    
                BodyStyle = WebMessageBodyStyle.WrappedRequest)]
    
            public Department
    
                AddStudentToDepartment(Department department, Student student)
    
            {
    
                List<Student> Students = department.Students;
    
                Students.Add(student);
    
    
    
                return department;
    
            }
    
        }

    3.3プロファイルwebを設定する.config


    View Code
    <?xml version="1.0"?>
    
    <configuration>
    
    
    
      <system.web>
    
        <compilation debug="true" targetFramework="4.0" />
    
      </system.web>
    
    
    
      <system.serviceModel>
    
        <serviceHostingEnvironment aspNetCompatibilityEnabled="true"
    
          multipleSiteBindingsEnabled="true" />
    
        <standardEndpoints>
    
          <webHttpEndpoint>
    
            <standardEndpoint name="" helpEnabled="true" automaticFormatSelectionEnabled="true" />
    
          </webHttpEndpoint>
    
        </standardEndpoints>
    
      </system.serviceModel>
    
      
    
     <system.webServer>
    
        <modules runAllManagedModulesForAllRequests="true"/>
    
      </system.webServer>
    
      
    
    </configuration>

    3.4 Global.asaxにイベントを追加


    View Code
    public class Global : System.Web.HttpApplication
    
        {
    
            protected void Application_Start(object sender, EventArgs e)
    
            {
    
                RouteTable.Routes.Add(new ServiceRoute("", new WebServiceHostFactory(), typeof(Service)));
    
            }
    
    
    
            protected void Application_BeginRequest(object sender, EventArgs e)
    
            {
    
    
    
                    HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
    
                    HttpContext.Current.Response.Cache.SetNoStore();
    
                    
    
                    EnableCrossDmainAjaxCall();
    
            }
    
    
    
            private void EnableCrossDmainAjaxCall()
    
            {
    
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
    
                if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
    
                {
    
                    HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST");
    
                    HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
    
                    HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
    
                    HttpContext.Current.Response.End();
    
                }
    
            }
    
        }

    以上の手順でwcf restを確立し、テストして使用することができます.うんてんこうじhttp://localhost:4305/help、インタフェースは次のとおりです.
     
    私たちが設定したリソースと同じです.
    4.コード解読
    4.1[ServiceContract]定義サービス
    4.2[WebGet(UriTemplate="/")]は、サイトルートパスを使用して、対応するコンテンツを取得し、基本的にgetメソッドです.
    http://localhost:4305/、ページ面を入力すると出力されます
    gsw02010gsw12011gsw22012gsw32013gsw42014gsw52015gsw62016gsw72017gsw82018gsw92019gsw
    これはちょうどGetAllIssuesメソッドが返す内容です.
    http://localhost:4305/Service/GetDepartment,会表示学生処北京大学
    4.3 UriTemplateはuriを指定します.
    4.4 WebGetAttributeは、スケジューラメソッドがHTTP GET要求に応答すべきであることを示す.WebInvokeAttributeプリセットはHTTP POSTにマッピングするが、WebInvokeAttribute.Methodプロパティは、他のすべてのHTTP動詞をサポートするように設定されています(PUTとDELETEは最も一般的な2つです).URIプリセットは、メソッドの名前によって決定される(エンドポイントのベースURIに追加される).
    4.5出力タイプを指定できます
    5.クライアントコール
    5.1コードコール
    5.1.1 get文
       HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create("http://localhost:4305/Service/GetDepartment");
    
                HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
    
                 DataContractJsonSerializer json = new DataContractJsonSerializer(typeof(Department));
    
                 object o = json.ReadObject(resp.GetResponseStream());
    
                 Department d = (Department)o;

    5.1.2 post文
    サーバ側uriを変更し、このメソッドは、Departmentをコミットし、Departmentタイプを返し、設定するだけです.
     department.SchoolName = "test";
        [OperationContract]
    
            [WebInvoke(Method ="POST", UriTemplate = "Service/AddStudentToDepartment",
    
                RequestFormat = WebMessageFormat.Json,BodyStyle = WebMessageBodyStyle.Bare
    
                ,ResponseFormat=WebMessageFormat.Json)]
    
            public Department
    
                AddStudentToDepartment(Department department)
    
            {
    
                //List<Student> Students = department.Students;
    
                //Students.Add(student);
    
                department.SchoolName = "test";
    
                return department;
    
            }

    クライアントコール:
      WebClient clent = new WebClient();
    
                Department department = new Department();
    
                department.DepartmentName = "   ";
    
                department.SchoolName = "    ";
    
                department.Students = new List<Student>();
    
                department.Students.Add(new Student() { ID = 12, Name = "gsw", Score = 34, State = " " });
    
                MemoryStream ms = new MemoryStream();
    
                DataContractJsonSerializer serializerToupdata = new DataContractJsonSerializer(typeof(Department));
    
                serializerToupdata.WriteObject(ms, department);
    
      
    
                clent.Headers["Content-type"] = "application/json";
    
                //
    
                 byte[] bytes= clent.UploadData("http://localhost:4305/Service/AddStudentToDepartment", "POST", ms.ToArray());
    
    
    
                 ms = new MemoryStream(bytes);
    
                 serializerToupdata = new DataContractJsonSerializer(typeof(Department));
    
    
    
                 object o = serializerToupdata.ReadObject(ms);
    
                 Department d = (Department)o;

    最良のdオブジェクト、SchoolNameは「test」で、コミットに成功し、読み取りに成功したことを示します.
     
    5.2 jquery呼び出し


    View Code
    <script type="text/javascript">
    
        $(document).ready(function () {
    
            $.ajax({
    
                cache: false,
    
                type: "GET",
    
                async: false,
    
                dataType: "json",
    
                url: "http://localhost:4305/",
    
                success: function (department1) {
    
                //    
    
                    alert(department1.SchoolName);
    
                },
    
                error: function (xhr) {
    
                    alert(xhr.responseText);
    
                }
    
            });
    
        });
    
    </script>

    http://localhost:4305/方メソッドを呼び出し、IssuesCollectionタイプを返し、alert(department 1.SchoolName)を出力します.