Using ASP.Net WebAPI with Web Forms

Asp.Net WebAPI is a framework for building RESTful HTTP services which can be used across a wide range of clients including web, phone and desktop applications. With WebAPI we can use XML and JSON to send and retrieve data from the service. The use of Json or XML makes it quite flexible to be used [

Asp.Net WebAPI is a framework for building RESTful HTTP services which can be used across a wide range of clients including web, phone and desktop applications. With WebAPI we can use XML and JSON to send and retrieve data from the service. The use of Json or XML makes it quite flexible to be used across a variety of devices.

Although WebAPI ships and installs with ASP.Net MVC 4, it can be used in normal Web Forms application as well.

In this example, we will use WebAPI with a traditional Web Forms application for adding and displaying a list of User Information. We will be using Visual Studio 2012 and .Net 4.5.

Creating the Project

Open Visual Studio 2012, Go To New -> Project. Select Visual C# -> Web from the left hand navigation and select project type as ASP.Net Web Forms Application. Enter the project name as WebAPIDemo

A new project will be created with a default template and our solution will show the following structure

Adding Model Class

We will then add a Model Class to our project. The Model class will represent the data in our application. We will add a model class called Users in our project

Right Click the Project in the Solution Explorer, Select Add -> Class from the Context Menu. The name of the class will be “Users” and it will have the following properties

Hide   Copy Code

namespace WebAPIDemo
{
    public class Users
    {
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Company { get; set; }
        public string Email { get; set; }
        public string PhoneNo { get; set; }
    }
}

The WebAPI can automatically serialize the model as JSON or XML object and will write the data in the body of the HTTP response. If the clients can read the serialize data, they will be able to deserialize it. Most of the clients are able to read the XML or JSON data. The clients can also specify the format it wants by setting the “Accept Header” property in the request message.

Creating The Repository

Ideally in a production scenario, we should be storing our data in some sort of persistent storage like database but to keep this demo simple, we will storing it in local memory.

To keep our storage implementation separate from the application code, we will be using Repository pattern. This way we can change our storage implementation at any future data without many changes to the application code.

We will start by creating a generic repository interface. Add a new class to the project and call it“IUserRepository”. It will have the following code

Hide   Copy Code

namespace WebAPIDemo
{
    public interface IUserRepository
    {
        IEnumerable<Users> GetAllUsers();
        string AddUser(Users user);
        Users GetUserById(int id);
        void DeleteUser(int id);
    }
}

The “GetAllUsers” function return a list of the all the users. The “AddUser” function will add a new user and“GetUserById” will return a particular user based on the id that has been passed.

Add a Class to the solution called “UserRepository”. The class will implement the “IUserRepository” and will have the following implementation.

Hide   Shrink    Copy Code

namespace WebAPIDemo
{
    public class UserRepository : IUserRepository
    {
        private List<Users> userList = new List<Users>();
        private int _id = 3;
        public UserRepository()
        {
 userList.Add(new Users { Id = 1, FirstName = "Madhur", LastName = "Kapoor", Company = "ABC", Email = "[email protected]", PhoneNo = "65431546" });
userList.Add(new Users { Id = 2, FirstName = "Alan", LastName = "Wake", Company = "XYZ Corp", Email = "[email protected]", PhoneNo = "64649879" });
        }
        public IEnumerable<Users> GetAllUsers()
        {
            return userList;
        }
        public string AddUser(Users user)
        {
            user.Id = _id++;
            userList.Add(user);
            return "User added";
        }
        public Users GetUserById(int id)
        {
            var user = userList.FirstOrDefault<Users>((p) => p.Id == id);
            if (user == null)
            {
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }
            return user;
        }
        public void DeleteUser(int id)
        {
            var user = userList.FirstOrDefault<users>((p) => p.Id == id);

            if (user == null)
            {
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }

            userList.Remove(user);
        }
    }</users>

In the class, we are using a local variable “userList” to store all the users. In the constructor, we are adding a few records to the list.

The “AddUser” function adds a new user to the list with a new Id.

The “GetUserByID” function uses a LINQ query to return the user with the specified id. If the user is not found, an HTTPResponseException is thrown which is interpreted by browser as “404” error.

You will need to add a reference to the “System.Web.Http” for the HttpResponseException class to work.

Creating The WebAPI Controller

We will now add a WebAPI controller to the solution. A WebAPI controller is a class that handles the HTTP request by the clients. WebAPI Controllers are similar to MVC Controllers except they derive from “ApiController” class instead of “Controller” class.

Right Click the solution, select Add -> Web API Controller Class. Name the Controller class as “UserController”.

The controller class will have some default function for Get, Put, Delete etc. Delete those functions and add the following functions so the code will look like below.

Hide   Copy Code

namespace WebAPIDemo
{
    public class UserController : ApiController
    {
        static IUserRepository repository = new UserRepository();

        public IEnumerable&lt;Users&gt; GetAllUsers()
        {
            var users = repository.GetAllUsers();
            return users;
        }

        public Users GetUserById(int id)
        {
            var user = repository.GetUserById(id);
            return user;
        }
        public string AddUser(Users user)
        {  var response = repository.AddUser(user);
            return response;
        }
        public void DeleteUser(int id)
        {
            repository.DeleteUser(id);
        }
    }
}

Adding Route in Global.asax

For the controller to handle requests of a particular type, we will have to define a route in the Global.asax file.

Open global.asax file and add the following code in the “Application_Start” method

Hide   Copy Code

RouteTable.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = System.Web.Http.RouteParameter.Optional }
            );

The controller will now be able to handle request of type “api/User/”

Testing The WebAPI

We will now Test our WebAPI by running it in the browser. Run the Web Application by pressing “Ctrl + F5” or going to “Debug -> Start Debugging” from the Visual Studio menu.

On running the application, the “Default.aspx” page will open. The URL will be something likehttp://localhost:56851/Default.aspx where 56851 will be port number.

To Test the WebAPI,  we will have to use the URL as defined in the Route. Enter the following URL in the browserhttp://localhost:56851/api/User/ (Replace 56851 with your port number)

The result will depend upon the type of browser you are using. In Internet Explorer, you will be prompted to save a file named “User”.

The file contains the Http response. Select “Open” and in the “Open with” dialog, select “Notepad” to open the file.

The Notepad will show the data in the JSON format which has been returned by the WebAPI.

[{"Id":1,"FirstName":"Madhur","LastName":"Kapoor","Company":"ABC","Email":"[email protected]","PhoneNo":"65431546"},{"Id":1,"FirstName":"Alan","LastName":"Wake","Company":"XYZ Corp","Email":"[email protected]","PhoneNo":"64649879"}]

If you are using Chrome or Firefox, you are likely to get a XML representation of the data. This is because Internet Explorer and Firefox send different “Accept Header” with the request and so the WebAPI returns different content type.

If you are using Internet Explorer with Developer tools, you can check the Request header that is being sent by the browser.

Just Open the Developer tools by pressing F12, go to network option and Enable “Start Capturing” and then with developer tools open, enter the WebAPI URL in the browser and press enter

If you use the following URL “ http://localhost:56851/api/User/1 (Replace 56851 with your port number)”

It will return the user whose ID is ‘1’. Typing an ID that does not exist will result in a “Page Not Found” error.

Calling WebAPI with JQuery

Now we will call the WebAPI using JQuery and will display the result in a web page.

In the “Default.aspx” file, we will use the following code for the body section to display the data

Hide   Shrink    Copy Code

<asp:Content runat="server" ID="BodyContent" ContentPlaceHolderID="MainContent">
<h2>My Address Book</h2>
    <br />
    <table>
        <thead>
            <tr>
                <td>Id</td>
                <td>Full Name</td>
                <td>Company</td>
                <td>Phone</td>
                <td>Email</td>
            </tr>
        </thead>
        <tbody id="usersection">
        </tbody>
    </table>
    <br />
    <br />
        <h2> Add A Contact</h2>
        <table>
        <tr>
            <td>First Name</td>
            <td>
                <asp:TextBox runat="server" ID="txtFirstName" /></td>
        </tr>
        <tr>
            <td>Last Name</td>
            <td>
                <asp:TextBox runat="server" ID="txtLastName" /></td>
        </tr>
        <tr>
            <td>Company</td>
            <td>
                <asp:TextBox runat="server" ID="txtCompany" /></td>
        </tr>
        <tr>
            <td>Phone</td>
            <td>
                <asp:TextBox runat="server" ID="txtPhone" /></td>
        </tr>
        <tr>
            <td>Email</td>
            <td>
                <asp:TextBox runat="server" ID="txtEmail" /></td>
        </tr>
        <tr>
            <td>
                <asp:Button Text="Save" runat="server" ID="btnSave"  />
            </td>
        </tr>
    </table>
    <br />
    <br />
    <asp:TextBox ID="txtSearch" runat="server"  />
    <asp:Button ID="btnSearch" runat="server" Text="Search" OnClientClick="search();return false;" />
    <br />
    <br />
    <p id="searchResult" >
    </p>
<br />
    <br />
    <asp:TextBox ID="txtDelete" runat="server"  />
    <asp:Button ID="btnDelete" runat="server" Text="Delete" OnClientClick="deleteuser();return false;" />
         </asp:Content>

Include a reference to JQuery in your project in the head section

Hide   Copy Code

<script src="Scripts/jquery-1.7.1.js" type="text/javascript"></script>

Getting list Of Users

To get a list of users, we will send a Get Request to the “api/User”

Hide   Copy Code

$(document).ready(function () {
            $.getJSON("api/User", function (data) {
                $(‘#usersection‘).empty();
                $.each(data, function (key, val) {
                    var row = "<tr><td>" + val.Id + "</td><td>" + val.LastName + ", " + val.FirstName + "</td><td>" + val.Company +
                        "</td><td>" + val.PhoneNo + "</td><td>" + val.Email + "</td></tr>";
                    $(row).appendTo($(‘#usersection‘));
                });
            });
        });

We use the “getJSON” JQuery function to send the GET Request specifying the URL. The second parameter is the callback function which will be called once the request is completed successfully. The “data” object will contains a list of JSON or XML objects which will be returned by the service.

Once we get the “data” from the API, we are iterating through the data and appending it to the body section of the table.

The “getJSON” function is called in the “document.ready” function so that it executed immediately when the page executes. On running the application now, you will get the following page

The default records which we added are displayed

Adding a User

We will now add a user using a Post Request using JQuery Ajax. As you can see, we have already created a form for entering the data. Once the save button is clicked, the following function is called

Hide   Copy Code

function insertData() {
            var Emp = {};
            Emp.FirstName = $("#<%=txtFirstName.ClientID %>").val();
            Emp.LastName = $("#<%=txtLastName.ClientID %>").val();
            Emp.PhoneNo = $("#<%=txtPhone.ClientID %>").val();
            Emp.Company = $("#<%=txtCompany.ClientID %>").val();
            Emp.Email = $("#<%=txtEmail.ClientID %>").val();
            $.ajax({
                url: "<%=Page.ResolveUrl("/api/User/AddUser")%>",
                type: "POST",
                contentType: "application/json;charset=utf-8",
                data: JSON.stringify(Emp),
                dataType: "json",
                success: function (response) {
                    alert(response);
                    getAllContacts();
                },
                error: function (x, e) {
                    alert(‘Failed‘);
                    alert(x.responseText);
                    alert(x.status);
                }
            });
        }

We are using the “ajax” method of JQuery to send a POST request to the the “api/User/AddUser” URL. As the“AddUser” function expects an object of type “User”, we create a JSON object and pass it with the request. The“success” function will be called if the request is successful and the response will be shown. In case of any error, the “error” function will be called.

Try adding a User. If everything is successful, you will get the following response. (Note: Ideally there should be validation on user input, for keeping the tutorial simple, I have not added any validation)

On Clicking Ok, the list will be updated and the new added user will be visible

Adding Search Function

To get a User by ID, we will call the “api/User/Id” passing the id of the user we want to display.

The code which is going to get called on Search button click will be

Hide   Copy Code

        function search() {
            var id = $(‘#<%=txtSearch.ClientID %>‘).val();
            $.getJSON("api/User/" + id,
                function (data) {
                    var str = data.Id + ‘ - ‘ + data.LastName + ", " + data.FirstName + " - " + data.Company;
                    $(‘#searchResult‘).text(str);
                })
            .fail(
                function (jqXHR, textStatus, err) {
                    $(‘#searchResult‘).text(‘Error: ‘ + err);
                });
        }

We call the Jquery “getJSON” function but this time we are passing the ID with the URL and the API will return a single JSON object if the User is found.

If no user exists with the ID, we will get an error as shown below

Adding Delete Functionality

To Delete the User, we will call the "api/User/id" and we will pass the id of the user which we want to delete. This time we will call the function using the Delete Http verb.

Here is the function which is getting called on Delete button click

Hide   Copy Code

 function deleteuser() {
            var id = $(‘#<%=txtDelete.ClientID %>‘).val();
            $.ajax({
                url: "<%=Page.ResolveUrl("/api/User/")%>" + id,
                  type: "DELETE",
                  contentType: "application/json;charset=utf-8",
                  success: function (response) {

                      alert("User Deleted");
                      getAllContacts();

                },

                  error: function (x, e) {
                      alert("Id Not Found");

                  }
              });
         }

If the id is not found, a 404 exception will be raised else the user will be deleted.

The Complete Code for the Default.aspx file can be found in the attached solution

We can also add the Update functionality to the application in similar manner. WebAPI can be used with Asp.Net MVC in a similar fashion.

Do leave your feedback and issues in the comments.

时间: 2024-10-16 09:22:12

Using ASP.Net WebAPI with Web Forms的相关文章

在asp.net WebAPI 中 使用Forms认证和ModelValidata(模型验证)

一.Forms认证 1.在webapi项目中启用Forms认证 Why:为什么要在WebAPI中使用Forms认证?因为其它项目使用的是Forms认证. What:什么是Forms认证?它在WebAPI中就是一个MessageHandle,具体请查找关键字“ASP.NET Forms” How:如何启动Forms认证? 最简单的是通过配置启动Forms认证: 1 <system.web> 2 <authentication mode="Forms"> 3 <

Adding ASP.NET Identity to an Empty or Existing Web Forms Project

By Raquel Soares De Almeida|October 23, 2013 This tutorial shows you how to add ASP.NET Identity (the new membership system for ASP.NET) to an ASP.NET application. When you create a new Web Forms or MVC project in Visual Studio 2013 RTM with Individu

ASP.NET Web Forms 4.5的新特性

作者:Parry出处:http://www.cnblogs.com/parry/ 一.强类型数据控件 在出现强类型数据控件前,我们绑定数据控件时,前台一般使用Eval或者DataBinder.Eval(Container.DataItem,"FieldName")的形式. 1 <%# DataBinder.Eval(Container.DataItem,"FieldName") %>2 <%# Eval("FieldName")

ASP.NET Web Forms 的 DI 應用範例

跟 ASP.NET MVC 与 Web API 比起来,在 Web Forms 应用程式中使用 Dependency Injection 要来的麻烦些.这里用一个范例来说明如何注入相依物件至 Web Forms 的 ASPX 页面. 使用的开发工具与类别库: Visual Studio 2013 .NET Framework 4.5 Unity 3.5.x 问题描述 基于测试或其他原因,希望 ASPX 网页只依赖特定服务的介面,而不要依赖具象类别. 假设首页 Default.aspx 需要一个传

在ASP.NET Web Forms中使用页面导出伪xls Excel表格

将数据导出为Excel表格是比较常见的需求,也有很多组件支持导出真正的Excel表格.由于Excel能打开HTML文件,并支持其中的table元素以及p之类的文本元素的显示,所以把.html扩展名改为.xls是比较常用的一种方式.当然这只是一种骗人的伎俩,所以我称之为伪xls表格.不过对于要求不高的需求,这种方法还是比较简单快捷的. 在Web Forms项目中,除了用代码拼凑HTML元素标记外,还可以直接用窗体页面渲染HTML表格.Web Forms就是用来渲染动态HTML的,直接利用它,支持代

五张图概括 什么是 ASP 、 ASP.NET (Web Pages,Web Forms ,MVC )

当你看懂下面这五张图,我相信你对于学习.NET Web开发路线将不陌生!                                               来源: http://www.w3school.com.cn/ ASP   ASP.NET Web Pages Web Forms MVC 建议结合 : http://msdn.microsoft.com/  学习  !

ASP.NET Web Forms的改进

虽然ASP.NET Web Forms不是vNext计划的一部分,但它并没有被忽视.作为Visual Studio 2013 Update 2的一部分,它重新开始支持新工具.EF集成和Roslyn. 为什么Web Forms不是ASP.NET vNext的一部分 作为开始,让我们先为这个坏消息做下解释.为了改进性能和跨平台可移植性,ASP.NET vNext正在消除对System.Web的依赖.与OWIN相比,它缓慢而庞大,使测试工作多了不必要的麻烦. 虽然他们已经多次尝试将其分离出来,但Web

Asp.Net Web Forms/MVC/Console App中使用Autofac

本来简单介绍了Autofac在Asp.Net Web Forms中的应用,后来又添加了mvc.控制台应用程序中使用Autofac,详情请看源码. ASP.NET Web Forms使用Autofac,至少需要一下步骤: 1,引用Autofac程序集. 2,添加Autofac Web Modules 到 Web.config. 3,在Global.asax中实现IContainerProviderAccessor接口. 我们创建一个ASP.NET Web Forms项目,命名为WebFormStu

在ASP.NET Web Forms中用System.Web.Optimization取代SquishIt

将一个ASP.NET Web Forms项目从.NET Framework 4.0升级至.NET Framework 4.5之后,发现SquishIt竟然引发了HTTP Error 500.0 - Internal Server Error. SquishIt是一个开源的支持ASP.NET的js/css打包工具,项目地址:https://github.com/jetheredge/SquishIt,出生早于Microsoft ASP.NET Web Optimization Framework(