search
HomeBackend DevelopmentC#.Net TutorialHow to build WebAPI under Webforms?

How to build WebAPI under Webforms?

Jun 23, 2017 pm 04:27 PM
apiwebwebapibuild

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 }
            );
        }
    }
}

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);
}

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);
        }

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

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

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
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
Mastering C# .NET Design Patterns: From Singleton to Dependency InjectionMastering C# .NET Design Patterns: From Singleton to Dependency InjectionMay 09, 2025 am 12:15 AM

Design patterns in C#.NET include Singleton patterns and dependency injection. 1.Singleton mode ensures that there is only one instance of the class, which is suitable for scenarios where global access points are required, but attention should be paid to thread safety and abuse issues. 2. Dependency injection improves code flexibility and testability by injecting dependencies. It is often used for constructor injection, but it is necessary to avoid excessive use to increase complexity.

C# .NET in the Modern World: Applications and IndustriesC# .NET in the Modern World: Applications and IndustriesMay 08, 2025 am 12:08 AM

C#.NET is widely used in the modern world in the fields of game development, financial services, the Internet of Things and cloud computing. 1) In game development, use C# to program through the Unity engine. 2) In the field of financial services, C#.NET is used to develop high-performance trading systems and data analysis tools. 3) In terms of IoT and cloud computing, C#.NET provides support through Azure services to develop device control logic and data processing.

C# .NET Framework vs. .NET Core/5/6: What's the Difference?C# .NET Framework vs. .NET Core/5/6: What's the Difference?May 07, 2025 am 12:06 AM

.NETFrameworkisWindows-centric,while.NETCore/5/6supportscross-platformdevelopment.1).NETFramework,since2002,isidealforWindowsapplicationsbutlimitedincross-platformcapabilities.2).NETCore,from2016,anditsevolutions(.NET5/6)offerbetterperformance,cross-

The Community of C# .NET Developers: Resources and SupportThe Community of C# .NET Developers: Resources and SupportMay 06, 2025 am 12:11 AM

The C#.NET developer community provides rich resources and support, including: 1. Microsoft's official documents, 2. Community forums such as StackOverflow and Reddit, and 3. Open source projects on GitHub. These resources help developers improve their programming skills from basic learning to advanced applications.

The C# .NET Advantage: Features, Benefits, and Use CasesThe C# .NET Advantage: Features, Benefits, and Use CasesMay 05, 2025 am 12:01 AM

The advantages of C#.NET include: 1) Language features, such as asynchronous programming simplifies development; 2) Performance and reliability, improving efficiency through JIT compilation and garbage collection mechanisms; 3) Cross-platform support, .NETCore expands application scenarios; 4) A wide range of practical applications, with outstanding performance from the Web to desktop and game development.

Is C# Always Associated with .NET? Exploring AlternativesIs C# Always Associated with .NET? Exploring AlternativesMay 04, 2025 am 12:06 AM

C# is not always tied to .NET. 1) C# can run in the Mono runtime environment and is suitable for Linux and macOS. 2) In the Unity game engine, C# is used for scripting and does not rely on the .NET framework. 3) C# can also be used for embedded system development, such as .NETMicroFramework.

The .NET Ecosystem: C#'s Role and BeyondThe .NET Ecosystem: C#'s Role and BeyondMay 03, 2025 am 12:04 AM

C# plays a core role in the .NET ecosystem and is the preferred language for developers. 1) C# provides efficient and easy-to-use programming methods, combining the advantages of C, C and Java. 2) Execute through .NET runtime (CLR) to ensure efficient cross-platform operation. 3) C# supports basic to advanced usage, such as LINQ and asynchronous programming. 4) Optimization and best practices include using StringBuilder and asynchronous programming to improve performance and maintainability.

C# as a .NET Language: The Foundation of the EcosystemC# as a .NET Language: The Foundation of the EcosystemMay 02, 2025 am 12:01 AM

C# is a programming language released by Microsoft in 2000, aiming to combine the power of C and the simplicity of Java. 1.C# is a type-safe, object-oriented programming language that supports encapsulation, inheritance and polymorphism. 2. The compilation process of C# converts the code into an intermediate language (IL), and then compiles it into machine code execution in the .NET runtime environment (CLR). 3. The basic usage of C# includes variable declarations, control flows and function definitions, while advanced usages cover asynchronous programming, LINQ and delegates, etc. 4. Common errors include type mismatch and null reference exceptions, which can be debugged through debugger, exception handling and logging. 5. Performance optimization suggestions include the use of LINQ, asynchronous programming, and improving code readability.

See all articles

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

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools