小小的快乐功能#2-Visual Studio 2012中的ASP.NET Web API

2024-02-16 13:59

本文主要是介绍小小的快乐功能#2-Visual Studio 2012中的ASP.NET Web API,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

REST, POX, and WCF compared to RESTtafarians, a guy with a bag on his head and Darth Vader

(UPDATE: See other Tiny Happy Features)

(更新:请参见其他Tiny Happy功能)

At some point soon lots of people are going to start writing these epic blog posts about Visual Studio 2012. They will include LOTS of screenshots (some good and some bad), some small code samples and minimal context. I can't speak for other teams; I can only talk about what we worked on. The <AngleBrackets/> folks in Azure Platform and Tools (ASP.NET, IIS, WCF, EF, Azure much and more) have been putting a lot of work into what I sometimes call "Death by a Thousand Tiny Cuts." It's the little irritants that are as frustrating (or more so) as the big missing features.

在不久的某个时刻,许多人将开始写有关Visual Studio 2012的史诗般的博客文章。它们将包括很多屏幕截图(有些好坏),一些小代码示例和最少的上下文。 我不能代表其他球队; 我只能谈论我们的工作。 Azure平台和工具(ASP.NET,IIS,WCF,EF,Azure等等)中的<AngleBrackets />成员已经为我有时称为“千刀斩死”的内容做了很多工作。 小刺激物与大缺失功能一样令人沮丧(或更多)。

Rather than a giant super post (although I'll do that at some point) I thought I'd showcase some Tiny Happy Features that the team worked on just because it made life better. Some are large some are small, but all are tiny happy features.

我认为我会展示一些团队致力于的Tiny Happy Feature ,因为它可以使生活变得更好,而不是一个巨大的超级职位(尽管我会在某个时候这样做)。 有些很大,有些很小,但都是微不足道的快乐功能。

There's Enterprise Web Services that use SOAP and WS-*.* and they are great for many transactional or complex scenarios. Then there are lighter weight RESTful web services or "Web APIs" that use JSON, XML and respect all of the goodness and stability that is the HTTP specification.

有使用SOAP和WS-*。*的企业Web服务,它们非常适合许多事务性或复杂的场景。 然后是重量更轻的RESTful Web服务或“ Web API”,它们使用JSON,XML并尊重HTTP规范的所有优点和稳定性。

WCF is alive and well and ASP.NET is alive and well and there are reasons to use each technology. As this article says very well, "The world of SOAP and the world of HTTP services are very different. SOAP allows us to place all the knowledge required by our service in the message itself" vs. "you can use [Web APIs] to create HTTP services that only use the standard HTTP concepts (URIs and verbs), and to to create services that use more advanced HTTP features – request/response headers, hypermedia concepts etc."

WCF运行良好,ASP.NET运行良好,并且有使用每种技术的理由。 正如本文所说的,“ SOAP的世界和HTTP服务的世界是非常不同的。SOAP允许我们将服务所需的所有知识放置在消息本身中”与“您可以使用[Web API]来创建仅使用标准HTTP概念(URI和动词)的HTTP服务,并创建使用更高级的HTTP功能(请求/响应标头,超媒体概念等)的服务。”

Kelly Sommers wrote what I consider the best explanation of REST out there in "Clarifying REST." Whether you want to write RESTful resource-focused HTTP services or just POX or POJ (Plain Old XML or Plain Old JSON) services, you can do both with ASP.NET Web API. It's all part of the ASP.NET open source web stack.

凯利·索默斯( Kelly Sommers )在“澄清REST ”一书中写下了我认为是REST的最佳解释。无论您是要编写RESTful的,以资源为中心的HTTP服务,还是只编写POX或POJ(普通XML或纯JSON)服务,您都可以做到使用ASP.NET Web API。 所有这些都是ASP.NET开源Web堆栈的一部分。

Rick Strahl says that ASP.NET Web API is different than other frameworks because "it was built from the ground up around the HTTP protocol and its messaging semantics. Unlike WCF REST or ASP.NET AJAX with ASMX, it’s a brand new platform rather than bolted on technology that is supposed to work in the context of an existing framework. The strength of the new ASP.NET Web API is that it combines the best features of the platforms that came before it, to provide a comprehensive and very usable HTTP platform."

Rick Strahl说,ASP.NET Web API与其他框架有所不同,因为“它是围绕HTTP协议及其消息传递语义完全构建的。与WCF REST或带有ASMX的ASP.NET AJAX不同,它是一个全新的平台,而不是新的ASP.NET Web API的优点在于,它结合了应该在现有框架的上下文中使用的技术,从而结合了之前平台的最佳功能,从而提供了一个全面且非常有用的HTTP平台。 “。

I encourage you to check out Rick's excellent analysis. Here's the features of ASP.NET Web API Rick likes:

我鼓励您查看Rick的出色分析。 这是Rick喜欢的ASP.NET Web API的功能:

  • Strong Support for URL Routing to produce clean URLs using familiar MVC style routing semantics

    强烈支持URL路由,以使用熟悉的MVC样式路由语义生成干净的URL

  • Content Negotiation based on Accept headers for request and response serialization

    基于Accept标头的内容协商,用于请求和响应序列化

  • Support for a host of supported output formats including JSON, XML, ATOM

    支持多种受支持的输出格式,包括JSON,XML,ATOM

  • Strong default support for REST semantics but they are optional

    对REST语义的强默认支持,但它们是可选的

  • Easily extensible Formatter support to add new input/output types

    轻松扩展的Formatter支持以添加新的输入/输出类型

  • Deep support for more advanced HTTP features via HttpResponseMessage and HttpRequestMessage
    classes and strongly typed Enums to describe many HTTP operations

    通过HttpResponseMessage和HttpRequestMessage对更高级的HTTP功能的深入支持类和强类型的Enums来描述许多HTTP操作

  • Convention based design that drives you into doing the right thing for HTTP Services

    基于约定的设计,可带您为HTTP Services做正确的事

  • Very extensible, based on MVC like extensibility model of Formatters and Filters

    基于MVC(如格式化程序和过滤器的可扩展性模型),非常可扩展

  • Self-hostable in non-Web applications 

    可在非Web应用程序中自托管

  • Testable using testing concepts similar to MVC

    可使用类似于MVC的测试概念进行测试

ASP.NET Web API(ASP.NET Web API)

There's some lovely new samples at this Git Repository. Just "git clone https://git01.codeplex.com/aspnet" or download the zip. You can also familiarize yourself with ASP.NET and the Web API at the new http://www.asp.net/webapi site.

这个Git储存库中有一些可爱的新样本。 只需"git clone https://git01.codeplex.com/aspnet"或下载zip即可。 您还可以在新的http://www.asp.net/webapi网站上熟悉ASP.NET和Web API。

By the way, I'll be publishing a bunch (13!) of new videos showcasing Web API plus a lot of other Tiny Happy Features next week on the 15th. Each video will only be 5 minutes long and will be a great way to get up to speed on all the new tech over lunch.

顺便说一句,下周15日,我将发布一堆(13个!)展示Web API的新视频以及许多其他的Tiny Happy功能。 每个视频只有5分钟长,是在午餐时间快速掌握所有新技术的好方法。

To use the samples, follow the instructions on Henrik's blog post announcing them.

要使用这些示例,请按照Henrik在博客上宣布这些示例的说明进行操作。

Here's one nice little sample that will perhaps cause you to rethink what you can accomplish with ASP.NET web technologies. It's a console application that hosts ASP.NET Web API. To be clear, there's no IIS involved.

这是一个很好的小示例,它可能会使您重新考虑使用ASP.NET Web技术可以完成的工作。 这是一个托管ASP.NET Web API的控制台应用程序。 需要明确的是,不涉及IIS。

In the setup instructions we have to register a port and user with HTTP.sys so the Operating System knows it's OK for send our little self-hosted app HTTP traffic. If you're familiar with WCF you may have done this before.

在设置说明中,我们必须向HTTP.sys注册端口和用户,以便操作系统知道可以发送我们小的自托管应用HTTP流量。 如果您熟悉WCF,则可能之前已经做过。

Here's the server. It's a Console App, minus error handling for clarity.

这是服务器。 这是一个控制台应用程序,为清晰起见,减去了错误处理。

class Program
{
static readonly Uri _baseAddress = new Uri("http://localhost:50231/");

static void Main(string[] args)
{
// Set up server configuration
HttpSelfHostConfiguration config = new HttpSelfHostConfiguration(_baseAddress);

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

// Create server
var server = new HttpSelfHostServer(config);

// Start listening
server.OpenAsync().Wait();
Console.WriteLine("Listening on " + _baseAddress + " Hit ENTER to exit...");
Console.ReadLine();
server.CloseAsync().Wait();
}
}

That code sets up a route, starts the self-hosting process, and waits. Here's a controller at http://localhost:50231/Contact that will ECHO whatever contact you HTTP POST to it as content-type JSON. Note that Contact is a C# type as a parameter to Post().

该代码设置一条路由,开始自托管过程,然后等待。 这是位于http:// localhost:50231 / Contact的控制器,该控制器将回显与您联系的任何内容,并将其作为内容类型JSON进行HTTP POST。 请注意,Contact是一种C#类型,作为Post()的参数。

public class ContactController : ApiController
{
public Contact Post(Contact contact)
{
return contact;
}
}

If I want, I can do a POST from another command line using curl and send some JSON into the server.

如果我愿意,我可以使用curl从另一个命令行执行POST并将一些JSON发送到服务器中。

POSTing JSON from CURL to ASP.NET Web API

Here's the actual command line. The JSON is echo'ed back.

这是实际的命令行。 JSON被回显。

C:\>curl -X POST -H "Content-Type: application/json" -d "{ Name: 'Scott Guthrie', Age: 67}" http://localhost:50231/api/Contact

C:\>curl -X POST -H "Content-Type: application/json" -d "{ Name: 'Scott Guthrie', Age: 67}" http://localhost:50231/api/Contact

That's from the command line but I can also use System.Net.Http.HttpClient to make a call from .NET if I like:

那是从命令行开始的,但是如果我喜欢,我还可以使用System.Net.Http.HttpClient从.NET进行调用:

HttpClient client = new HttpClient();

Contact contact = new Contact {
Name = "Henrik",
Age = 100
};

// Post contact
Uri address = new Uri(_baseAddress, "/api/contact");
HttpResponseMessage response = await client.PostAsJsonAsync(address.ToString(), contact);

// Check that response was successful or throw exception
response.EnsureSuccessStatusCode();

// Read result as Contact
Contact result = await response.Content.ReadAsAsync<Contact>();

Console.WriteLine("Result: Name: {0} Age: {1}", result.Name, result.Age);

See how the C# Contact object moves back and forth between the JSON world and C# world easily? That's the JSON.NET open source library making that happen.

看到C#Contact对象如何轻松地在JSON世界和C#世界之间来回移动吗? 这就是实现这一点的JSON.NET开源库。

JSON and JavaScript is really dynamic, though, and often it's a hassle to try to "deserialize" really dynamic JSON objects into strongly-typed .NET structures. JSON.NET and ASP.NET Web API's model binding offer a happy medium - a middle ground - called JToken.

JSON和JavaScript确实是动态的,并且尝试将真正动态的JSON对象“反序列化”为强类型的.NET结构通常很麻烦。 JSON.NET和ASP.NET Web API的模型绑定提供了一种称为JToken的快乐媒介-一种中间立场。

public class ContactController : ApiController
{
public JToken Post(JToken contact)
{
return contact;
}
}

Check out the watch window as the JSON comes in:

当JSON出现时,请查看监视窗口:

Using JToken to catch a JSON payload

Using JToken gives me a dynamic container but also a DOM-like navigation model. But if that's not dynamic enough for me, why can't my method's parameter just take a "dynamic."

使用JToken给我一个动态的容器,但也给了我一个类似DOM的导航模型。 但是,如果这对我来说不够动态,那么为什么我的方法的参数不能仅仅采用“动态”。

C# is statically typed, sure, but that doesn't mean I can't statically type something dynamic. ;)

当然,C#是静态类型的,但这并不意味着我不能静态地动态类型。 ;)

Again, note the watch window.

再次注意观察窗口。

Using dynamic to catch JSON post payloads

See how JSON is moving around the system without any impedance mismatch. The power of C# isn't slowing down the flexibility of JavaScript and JSON.

了解JSON如何在系统中移动而没有任何阻抗失配。 C#的功能并没有减慢JavaScript和JSON的灵活性。

It makes me happy when things work as they should.

当事情按原样进行时,这使我感到高兴。

翻译自: https://www.hanselman.com/blog/tiny-happy-features-2-aspnet-web-api-in-visual-studio-2012

这篇关于小小的快乐功能#2-Visual Studio 2012中的ASP.NET Web API的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/714739

相关文章

苹果macOS 26 Tahoe主题功能大升级:可定制图标/高亮文本/文件夹颜色

《苹果macOS26Tahoe主题功能大升级:可定制图标/高亮文本/文件夹颜色》在整体系统设计方面,macOS26采用了全新的玻璃质感视觉风格,应用于Dock栏、应用图标以及桌面小部件等多个界面... 科技媒体 MACRumors 昨日(6 月 13 日)发布博文,报道称在 macOS 26 Tahoe 中

Java使用HttpClient实现图片下载与本地保存功能

《Java使用HttpClient实现图片下载与本地保存功能》在当今数字化时代,网络资源的获取与处理已成为软件开发中的常见需求,其中,图片作为网络上最常见的资源之一,其下载与保存功能在许多应用场景中都... 目录引言一、Apache HttpClient简介二、技术栈与环境准备三、实现图片下载与保存功能1.

MybatisPlus service接口功能介绍

《MybatisPlusservice接口功能介绍》:本文主要介绍MybatisPlusservice接口功能介绍,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友... 目录Service接口基本用法进阶用法总结:Lambda方法Service接口基本用法MyBATisP

Java反射实现多属性去重与分组功能

《Java反射实现多属性去重与分组功能》在Java开发中,​​List是一种非常常用的数据结构,通常我们会遇到这样的问题:如何处理​​List​​​中的相同字段?无论是去重还是分组,合理的操作可以提高... 目录一、开发环境与基础组件准备1.环境配置:2. 代码结构说明:二、基础反射工具:BeanUtils

Druid连接池实现自定义数据库密码加解密功能

《Druid连接池实现自定义数据库密码加解密功能》在现代应用开发中,数据安全是至关重要的,本文将介绍如何在​​Druid​​连接池中实现自定义的数据库密码加解密功能,有需要的小伙伴可以参考一下... 目录1. 环境准备2. 密码加密算法的选择3. 自定义 ​​DruidDataSource​​ 的密码解密3

python web 开发之Flask中间件与请求处理钩子的最佳实践

《pythonweb开发之Flask中间件与请求处理钩子的最佳实践》Flask作为轻量级Web框架,提供了灵活的请求处理机制,中间件和请求钩子允许开发者在请求处理的不同阶段插入自定义逻辑,实现诸如... 目录Flask中间件与请求处理钩子完全指南1. 引言2. 请求处理生命周期概述3. 请求钩子详解3.1

SpringCloud使用Nacos 配置中心实现配置自动刷新功能使用

《SpringCloud使用Nacos配置中心实现配置自动刷新功能使用》SpringCloud项目中使用Nacos作为配置中心可以方便开发及运维人员随时查看配置信息,及配置共享,并且Nacos支持配... 目录前言一、Nacos中集中配置方式?二、使用步骤1.使用$Value 注解2.使用@Configur

SpringBoot项目Web拦截器使用的多种方式

《SpringBoot项目Web拦截器使用的多种方式》在SpringBoot应用中,Web拦截器(Interceptor)是一种用于在请求处理的不同阶段执行自定义逻辑的机制,下面给大家介绍Sprin... 目录一、实现 HandlerInterceptor 接口1、创建HandlerInterceptor实

使用Python实现调用API获取图片存储到本地的方法

《使用Python实现调用API获取图片存储到本地的方法》开发一个自动化工具,用于从JSON数据源中提取图像ID,通过调用指定API获取未经压缩的原始图像文件,并确保下载结果与Postman等工具直接... 目录使用python实现调用API获取图片存储到本地1、项目概述2、核心功能3、环境准备4、代码实现

无法启动此程序因为计算机丢失api-ms-win-core-path-l1-1-0.dll修复方案

《无法启动此程序因为计算机丢失api-ms-win-core-path-l1-1-0.dll修复方案》:本文主要介绍了无法启动此程序,详细内容请阅读本文,希望能对你有所帮助... 在计算机使用过程中,我们经常会遇到一些错误提示,其中之一就是"api-ms-win-core-path-l1-1-0.dll丢失