Home Backend Development C#.Net Tutorial How to build WebAPI under Webforms?

How to build WebAPI under Webforms?

Jun 23, 2017 pm 04:27 PM
api web webapi build

Many of the company's projects have been using WebForms in the early stage. However, due to the development of business, the company needs to connect the mobile terminal to the original project. Webservice is a bit old, and RESTFul is more popular now, so WebAPI came to mind.

1. If it is the easiest to create a new project, file=>New=>Project=>Web=> ASP.NET Web application, check both Web Forms and Web API core references below. That's it, the webfroms core and WebAPI core applications are created.

How to build WebAPI under Webforms?

How to build WebAPI under Webforms?

2. If you are adding WebAPI to the original project, just reference the relevant package. .

1. Create the WebForms application first here

How to build WebAPI under Webforms?

How to build WebAPI under Webforms?

2. After the Webfroms project is created, you need to use VS NuGet package manager. Right-click the reference and select Manage NuGet Packages.

Select Browse, search for WebAPI, select the first Microsoft.AspNet.WebApi; click Install on the right and click OK, then select I accept, and wait until the output shows success, the installation is complete.

How to build WebAPI under Webforms?

How to build WebAPI under Webforms?

How to build WebAPI under Webforms?

3. Right-click the Web project and add the name App_Start folder, create a cs file named WebApiConfig under the App_Start folder.

Clean up the namespace, change the class to a static type, add necessary code, and self-reference for missing references.

How to build WebAPI under Webforms?

The complete code is as follows:

using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.Http;namespace WebFormsDemo
{public static class WebApiConfig
    {public static void Register(HttpConfiguration config)
        {// Web API 配置和服务// Web API 路由            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }
}
Copy after login

4. You need to register the WebAPI in the Application_Start method under the Global.asax file, here System.Web.Http needs to be referenced; the complete code is as follows:

protected void Application_Start(object sender, EventArgs e)
{// 在应用程序启动时运行的代码    GlobalConfiguration.Configure(WebApiConfig.Register);
}
Copy after login

5. Next, let us test it and create a new Controller

How to build WebAPI under Webforms?

6. The browser accesses http://localhost:27650/api/values/get?id=1 and the test passes.

How to build WebAPI under Webforms?

3. Use OWIN as the host to start Webapi

The above is to use Global method to start WebAPI. If SignalR is used in the project , you must use OWIN as the host. Although there are tutorials on the Internet that Global can also start SignalR (add RouteTable.Routes.MapHubs(); in the Application_Start method), Microsoft declared it obsolete as early as June 2014. , it is recommended to use Owin Startup Class to start SignalR. ()

1. Without further ado, create a new Startup class

How to build WebAPI under Webforms?

How to build WebAPI under Webforms?

2. Create a new one directly under the Configuration method A ConfigureWebapi method, the complete code is as follows:

        /// <summary>/// 配置Webapi/// </summary>/// <param>public void ConfigureWebapi(IAppBuilder app)
        {//创建一个HTTP的实例配置HttpConfiguration config = new HttpConfiguration();//映射路由            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );//将配置注入OWIN管道中            app.UseWebApi(config);
        }
Copy after login

How to build WebAPI under Webforms?

3. We found that there is an error message that UseWebApi is not included in IAppBuilder Definition, the reason is the lack of Self-Host hosting support, enter the following command in the package manager console:

Install-Package Microsoft.AspNet.WebApi.OwinSelfHost
Copy after login

How to build WebAPI under Webforms?

4.安装完成后错误提示消失

How to build WebAPI under Webforms?

5.移除Global中的启动方式,并将ConfigureWebapi方法初始化。

How to build WebAPI under Webforms?

How to build WebAPI under Webforms?

6.让我们来测试一下,http://localhost:27650/api/values/get?id=1,报错误404.

How to build WebAPI under Webforms?

7.原因是还缺少一个名为 Microsoft.Owin.Host.SystemWeb 的包,这个包提供了Owin服务运行ASP.NET 网络请求管道。在程序包管理器控制台,中输入以下指令:

install-package Microsoft.Owin.Host.SystemWeb
Copy after login

How to build WebAPI under Webforms?

8.让我们再来测试一下,浏览器中输入http://localhost:27650/api/values/get?id=1,测试通过。

How to build WebAPI under Webforms?

最后,值得一提的是官方的教程大多都使用隐式类型var 关键字,有网友说使用隐式类型的好处有

1.它有利于更好地为本地变量命名。
2. 它有利于设计更好的API。
3. 它促使对变量进行初始化。
4. 它消除了代码的混乱。
5. 它不需要using指示符。

楼主还没有深刻的体会和研究,不敢在这里妄加解释。还在学习中,下面是微软官方的文档,大家感受一下。

How to build WebAPI under Webforms?

文章到这里就结束了,其实写如何搭建WebAPI的文章也很多,这里仅仅是做一下记录,以防自己忘掉,如果此文章有幸被你看到,欢迎不吝指教。

The above is the detailed content of How to build WebAPI under Webforms?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1268
29
C# Tutorial
1246
24
Oracle API Usage Guide: Exploring Data Interface Technology Oracle API Usage Guide: Exploring Data Interface Technology Mar 07, 2024 am 11:12 AM

Oracle is a world-renowned database management system provider, and its API (Application Programming Interface) is a powerful tool that helps developers easily interact and integrate with Oracle databases. In this article, we will delve into the Oracle API usage guide, show readers how to utilize data interface technology during the development process, and provide specific code examples. 1.Oracle

How to deal with Laravel API error problems How to deal with Laravel API error problems Mar 06, 2024 pm 05:18 PM

Title: How to deal with Laravel API error problems, specific code examples are needed. When developing Laravel, API errors are often encountered. These errors may come from various reasons such as program code logic errors, database query problems, or external API request failures. How to handle these error reports is a key issue. This article will use specific code examples to demonstrate how to effectively handle Laravel API error reports. 1. Error handling in Laravel

Oracle API integration strategy analysis: achieving seamless communication between systems Oracle API integration strategy analysis: achieving seamless communication between systems Mar 07, 2024 pm 10:09 PM

OracleAPI integration strategy analysis: To achieve seamless communication between systems, specific code examples are required. In today's digital era, internal enterprise systems need to communicate with each other and share data, and OracleAPI is one of the important tools to help achieve seamless communication between systems. This article will start with the basic concepts and principles of OracleAPI, explore API integration strategies, and finally give specific code examples to help readers better understand and apply OracleAPI. 1. Basic Oracle API

What are web standards? What are web standards? Oct 18, 2023 pm 05:24 PM

Web standards are a set of specifications and guidelines developed by W3C and other related organizations. It includes standardization of HTML, CSS, JavaScript, DOM, Web accessibility and performance optimization. By following these standards, the compatibility of pages can be improved. , accessibility, maintainability and performance. The goal of web standards is to enable web content to be displayed and interacted consistently on different platforms, browsers and devices, providing better user experience and development efficiency.

Development suggestions: How to use the ThinkPHP framework for API development Development suggestions: How to use the ThinkPHP framework for API development Nov 22, 2023 pm 05:18 PM

Development suggestions: How to use the ThinkPHP framework for API development. With the continuous development of the Internet, the importance of API (Application Programming Interface) has become increasingly prominent. API is a bridge for communication between different applications. It can realize data sharing, function calling and other operations, and provides developers with a relatively simple and fast development method. As an excellent PHP development framework, the ThinkPHP framework is efficient, scalable and easy to use.

Can buildings be built in the wild in Mistlock Kingdom? Can buildings be built in the wild in Mistlock Kingdom? Mar 07, 2024 pm 08:28 PM

Players can collect different materials to build buildings when playing in the Mistlock Kingdom. Many players want to know whether to build buildings in the wild. Buildings cannot be built in the wild in the Mistlock Kingdom. They must be within the scope of the altar. . Can buildings be built in the wild in Mistlock Kingdom? Answer: No. 1. Buildings cannot be built in the wild areas of the Mist Lock Kingdom. 2. The building must be built within the scope of the altar. 3. Players can place the Spirit Fire Altar by themselves, but once they leave the range, they will not be able to construct buildings. 4. We can also directly dig a hole in the mountain as our home, so we don’t need to consume building materials. 5. There is a comfort mechanism in the buildings built by players themselves, that is to say, the better the interior, the higher the comfort. 6. High comfort will bring attribute bonuses to players, such as

How to enable administrative access from the cockpit web UI How to enable administrative access from the cockpit web UI Mar 20, 2024 pm 06:56 PM

Cockpit is a web-based graphical interface for Linux servers. It is mainly intended to make managing Linux servers easier for new/expert users. In this article, we will discuss Cockpit access modes and how to switch administrative access to Cockpit from CockpitWebUI. Content Topics: Cockpit Entry Modes Finding the Current Cockpit Access Mode Enable Administrative Access for Cockpit from CockpitWebUI Disabling Administrative Access for Cockpit from CockpitWebUI Conclusion Cockpit Entry Modes The cockpit has two access modes: Restricted Access: This is the default for the cockpit access mode. In this access mode you cannot access the web user from the cockpit

what does web mean what does web mean Jan 09, 2024 pm 04:50 PM

The web is a global wide area network, also known as the World Wide Web, which is an application form of the Internet. The Web is an information system based on hypertext and hypermedia, which allows users to browse and obtain information by jumping between different web pages through hyperlinks. The basis of the Web is the Internet, which uses unified and standardized protocols and languages ​​to enable data exchange and information sharing between different computers.

See all articles