Статьи

Как разработать приложение веб-службы ASP.NET с помощью службы WCF

В этой статье я собираюсь объяснить, как разрабатывать серверное приложение RESTFul для веб-служб на C #. Здесь я объясню, как обрабатывать запросы GET, POST, PUT и DELETE. Эта статья очень просто разработана так, чтобы всем было легко ее понять. Вы можете скачать проект здесь .

Если вы хотите узнать больше об услугах RESTFul и JSON, вы можете прочитать статьи ниже.

Что такое RESTFul сервис?

Я написал еще две статьи о веб-сервисе RESTFul в .net, они могут вам понравиться. 

Давайте начнем наш проект.

1. Сначала создайте проект веб-приложения ASP.NET в Visual Studio и назовите его StudentRegistrationDemo1.

Файл-> Новый-> Проект-> Веб-приложение ASP.NET (см. Окно ниже) и нажмите ОК.

Как только вы нажмете кнопку ОК, вы увидите окно ниже

Вы просто нажимаете OK и создаете пустой проект. 

Теперь ваш проектный фреймворк создан и вы можете увидеть его в своем обозревателе решений.

2 Теперь создайте папку с именем Dataobjects. Здесь мы создадим все классы для хранения нашей информации о регистрации студентов. В этом примере мы не используем базу данных.

3 Сначала создайте папку с именем Dataobject для хранения всех классов, необходимых для этого проекта. Щелкните правой кнопкой мыши проект в приведенном выше Обозревателе решений и выберите «Добавить», а затем в подокне выберите «Новая папка» и назовите ее «Объект данных».

4. Наш первый класс C # будет «Студенческий класс» для создания объекта ученика для хранения информации ученика. Щелкните правой кнопкой мыши папку Dataobject в приведенном выше Обозревателе решений и выберите Добавить. В подокне выберите Class, и вы увидите окно ниже. Теперь дайте этому классу имя Student и нажмите кнопку Add.

 Теперь добавьте следующий код.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace StudentRegistrationDemo1.Dataobject
{
    [Serializable]
    public class Student
    {

        String name;

        public String Name
        {
            get { return name; }
            set { name = value; }
        }

        int age;

        public int Age
        {
            get { return age; }
            set { age = value; }
        }

        String registrationNumber;

        public String RegistrationNumber
        {
            get { return registrationNumber; }
            set { registrationNumber = value; }
        }


    }
}

5 Нашим 2- м классом будет Студенческая регистрация. Это одноэлементный класс, который будет содержать список зарегистрированных студентов и все операции для запросов GET, POST, PUT и DELETE. Просто выполните шаг 4 выше, чтобы создать этот класс. Теперь добавьте следующие коды.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace StudentRegistrationDemo1.Dataobject
{
    public class StudentRegistration
    {
        Dictionary<string, Student> studentList;
        static StudentRegistration stdregd = null;

        private StudentRegistration()
        {
            studentList = new Dictionary<string, Student>();
        }

        public static StudentRegistration getInstance()
        {
            if (stdregd == null)
            {
                stdregd = new StudentRegistration();
                return stdregd;
            }
            else
            {
                return stdregd;
            }
        }

        public void Add(Student student)
        {
            studentList.Add(student.RegistrationNumber, student);
        }

        public Student Remove(String registrationNumber)
        {
            Student std;
            std = studentList[registrationNumber];
            studentList.Remove(registrationNumber);
            return std;
        }

        public Dictionary<string, Student> getAllStudent()
        {
            return studentList;
        }

        public Student getStudent(String registrationNum)
        {
            return studentList[registrationNum];
        }

        public String UpdateStudent(Student std)
        {
            String reply = "Student List Updated successfully";
            studentList[std.RegistrationNumber] = std;
            return reply;
        }


    }
 }

6. Теперь нам нужен класс для ответа на вызовы для POST. Всякий раз, когда мы добавляем запись ученика, он возвращает объект ниже с информацией ученика, который добавил в систему.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace StudentRegistrationDemo1.Dataobject
{
    public class StudentRegistrationReply
    {
        String name;

        public String Name
        {
            get { return name; }
            set { name = value; }
        }
        int age;

        public int Age
        {
            get { return age; }
            set { age = value; }
        }
        String registrationNumber;

        public String RegistrationNumber
        {
            get { return registrationNumber; }
            set { registrationNumber = value; }
        }
        String registrationStatus;

        public String RegistrationStatus
        {
            get { return registrationStatus; }
            set { registrationStatus = value; }
        }

    }
}

Теперь нам нужны все контроллеры для реализации вызовов веб-сервисов GET, POST, PUT и DELETE.

7 Теперь щелкните правой кнопкой мыши на проекте и добавьте папку с именем «Контроллеры» (выполните шаг 3). Эта папка будет содержать все необходимые классы контроллеров для сервисов GET, POST, PUT и DELETE. В этом примере мы создадим отдельный контроллер для запросов GET, POST, PUT и DELETE, даже если в этом нет необходимости, но мы покажем их для большей ясности. Для всех вышеперечисленных сервисов подойдет даже один контроллер, но в соответствии с хорошим принципом проектирования у нас должен быть отдельный контроллер, чтобы было легко поддерживать и отлаживать приложение. Сначала начните с запроса GET. Здесь мы создадим наш первый контроллер для обработки запроса GET и назовем его StudentRetrieveController. 

8 Теперь щелкните правой кнопкой мыши на папке «Controllers» в Solution Explorer и выберите Add-> NewItem. Теперь вы видите окно ниже, и из этого выберите «Служба WCF (с поддержкой Ajax)» и нажмите кнопку «Добавить». WCF обозначает Windows Communication Foundation. WCF — это библиотека для приложений различных платформ или одной и той же платформы для связи по различным протоколам, таким как TCP, HTTP, HTTPS. Ajax — это в основном асинхронный JavaScript и XML. AJAX позволяет асинхронно обновлять веб-страницы, обмениваясь небольшими объемами данных с сервером за кулисами.

Теперь откройте класс контроллера и добавьте приведенный ниже код после комментария // Добавьте дополнительные операции здесь и пометьте их [OperationContract] для обработки запроса GET.

        [OperationContract]
        [WebInvoke(Method = "GET", RequestFormat = WebMessageFormat.Json,
            UriTemplate = "/GetAllStudents/", ResponseFormat = WebMessageFormat.Json,
            BodyStyle = WebMessageBodyStyle.Wrapped)]

        public Dictionary<string, Student> GetAllStudents()
        {
            return StudentRegistration.getInstance().getAllStudent();
        }

Каждый раз, когда вы добавляете класс контроллера, добавляйте его ниже первой строки в разделе «использование»:  Using StudentRegistrationDemo1.Dataobject; 

9 Теперь нам нужно внести изменения в конфигурацию, чтобы включить этот веб-сервис RESTFul. Пожалуйста, не забудьте внести эти изменения, когда вы добавляете контроллер, иначе ваши службы не будут работать вообще. 

В обозревателе решений щелкните и откройте Web.config и найдите <enableWebScript>

Измените его на <webHttp />

10.  Сейчас самое время запустить и протестировать наш первый сервис. В строке меню вы можете увидеть зеленую кнопку со стрелкой, и вы можете выбрать браузер, установленный в вашей системе, и щелкнуть по нему. Он запустит ваш веб-сервер и запустит приложение веб-службы.

Теперь откроется окно браузера, как показано ниже:

Не разочаровывайтесь, увидев окно выше и не закрывайте его. Теперь сервер работает, и мы сделаем наш первый вызов веб-службы, т.е. сначала вызов GET. Просто скопируйте и вставьте приведенный ниже URL в адресную строку и нажмите кнопку ввода (имейте в виду, что номер порта в вашем случае должен быть другим. В моем случае это 53572. Измените его соответствующим образом). Теперь вы можете увидеть ниже:

HTTP: // локальный: 53572 / Контроллеры / StudentRetriveController.svc / GetAllStudents /

Поскольку мы не вставляли никаких записей в наше приложение, мы видим пустую запись JSON. Все идет нормально. Давайте добавим POST-сервис для хранения информации о студентах в нашей системе. Просто остановите приложение. 

11. Now follow step 8 and add a new controller called StudentRegistrationController for handling the HTTP request for POST calls. Once you create this controller, immediately follow step 9 and modify the web-config.xml file and add the below code in the controller class. Each time you add a controller class, please add the below line first in the “using” section. 

using StudentRegistrationDemo1.Dataobject;

        [OperationContract]
        [WebInvoke(Method = "POST",
            ResponseFormat = WebMessageFormat.Json,
            BodyStyle = WebMessageBodyStyle.Bare,
            UriTemplate = "/register.json")]
        public StudentRegistrationReply registerStudent(Student studentregd)
        {
            Console.WriteLine("In registerStudent");
            StudentRegistrationReply stdregreply = new StudentRegistrationReply();           
            StudentRegistration.getInstance().Add(studentregd);
            stdregreply.Name = studentregd.Name;
            stdregreply.Age = studentregd.Age;
            stdregreply.RegistrationNumber = studentregd.RegistrationNumber;
            stdregreply.RegistrationStatus = "Successful";

            return stdregreply;
        }

Now for the POST web service call, we will use the SOAPUI tool. Download the soap from here and install it in your system. It’s better to use the open source version, which is free. 

Now the real testing part:

12. Open the SOAPUI tool and go to file and select “New REST project.” A small window will appear like below, where you paste the below URL: http://localhost:53572/Controllers/StudentRegistrationController.svc/register.json for POST service call and click ok.

Now you can see the below window:

Now, first select Method as POST (By default it will display GET) and add below JSON block in “Media Type” window also from the combo box select media type as application/json. 

{

   “name”: “someName”,

   “age”: 25,

   “registrationNumber”: “12345”

} 

Now click the green arrow button, which will add the record to your system. Repeat this to insert 3 records with different values. Please keep in mind we have not used any exception handling here, hence, the registration number must be different each time.

After inserting 3 records, we will execute the GET call to see all these records. 

13. Now follow step 12 and create a project to test the GET request. Just copy and paste the below URL. Here, you don’t need to do anything just click the green arrow button. 

http://localhost:53572/Controllers/StudentRetriveController.svc/GetAllStudents/

In the above image, I have inserted three records, and in one record, I put the age as 100 so that I can modify it with the PUT call. 

14. Now add a new controller called StudentUpdateController and modify the Web.config file as mentioned in step 9 and add the below code in the controller class to handle PUT request.

            [WebInvoke(Method = "PUT",
            ResponseFormat = WebMessageFormat.Json,
            BodyStyle = WebMessageBodyStyle.Bare,
            UriTemplate = "/Update.json")]
        public String updateStudent(Student studentregd)
        {
            try
            {
                return StudentRegistration.getInstance().UpdateStudent(studentregd);
            }
            catch (Exception e)
            {
                return e.Message;
            }
        }

15. Now again, restart the server and insert 3 records. Then create one project for the PUT service call and add the records to be modified and click the green arrow button.

http://localhost:53572/Controllers/StudentUpdateController.svc/Update.json

Now follow step 13 and check the modified record.

16. Now, our last web service call is DELETE. Add a new controller called StudentDeleteController and add the below code. Modify web.config file and restart the server. Add three records and delete any one of them and check.

        [OperationContract]
        [WebInvoke(Method = "DELETE",
            ResponseFormat = WebMessageFormat.Json,
            BodyStyle = WebMessageBodyStyle.Bare,
            UriTemplate = "/delete.json/{registrationNumber}")]
        public Student DeleteStudent(String registrationNumber)
        {           
             return StudentRegistration.getInstance().Remove(registrationNumber); 

        }

Use the below URL and create a project for the DELETE web service call 

http://localhost:53572/Controllers/StudentDeleteController.svc/delete.json/12346 

In the above URL, 12346 is the registration number of a student.

In this article, I have not implemented any Exception Handler. I am leaving it to you as an exercise. Whenever implementing an exception handler in Web APIs, always keep in mind that your return type must be a generic type. In case of an exception, you might not return the actual return type but an Exception object or even a string. For example, in the below POST call, in the event of an exception, you are not going to return an object type «StudentRegistrationReply», rather, you will return an Exception object or an error message as a string object. Hence, you have to change the return type to IActionResult.

public IActionResult registerStudent(Student studentregd)
{
   //now you can return any object type
}

Also, I want you to implement a GET request, which will return a particular student based on his registration number.

I am giving you the example of the URLs for the same below:

http://localhost:53572/Controllers/StudentRetriveController.svc/GetStudent/12345

http://localhost:53572/Controllers/StudentRetriveController.svc/GetStudent?registrationNumber=12345

Thank you, and let me know of any questions in the comments.