小小的快乐功能#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

相关文章

Go语言实现将中文转化为拼音功能

《Go语言实现将中文转化为拼音功能》这篇文章主要为大家详细介绍了Go语言中如何实现将中文转化为拼音功能,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 有这么一个需求:新用户入职 创建一系列账号比较麻烦,打算通过接口传入姓名进行初始化。想把姓名转化成拼音。因为有些账号即需要中文也需要英

Spring常见错误之Web嵌套对象校验失效解决办法

《Spring常见错误之Web嵌套对象校验失效解决办法》:本文主要介绍Spring常见错误之Web嵌套对象校验失效解决的相关资料,通过在Phone对象上添加@Valid注解,问题得以解决,需要的朋... 目录问题复现案例解析问题修正总结  问题复现当开发一个学籍管理系统时,我们会提供了一个 API 接口去

基于WinForm+Halcon实现图像缩放与交互功能

《基于WinForm+Halcon实现图像缩放与交互功能》本文主要讲述在WinForm中结合Halcon实现图像缩放、平移及实时显示灰度值等交互功能,包括初始化窗口的不同方式,以及通过特定事件添加相应... 目录前言初始化窗口添加图像缩放功能添加图像平移功能添加实时显示灰度值功能示例代码总结最后前言本文将

使用IntelliJ IDEA创建简单的Java Web项目完整步骤

《使用IntelliJIDEA创建简单的JavaWeb项目完整步骤》:本文主要介绍如何使用IntelliJIDEA创建一个简单的JavaWeb项目,实现登录、注册和查看用户列表功能,使用Se... 目录前置准备项目功能实现步骤1. 创建项目2. 配置 Tomcat3. 项目文件结构4. 创建数据库和表5.

使用Python实现批量访问URL并解析XML响应功能

《使用Python实现批量访问URL并解析XML响应功能》在现代Web开发和数据抓取中,批量访问URL并解析响应内容是一个常见的需求,本文将详细介绍如何使用Python实现批量访问URL并解析XML响... 目录引言1. 背景与需求2. 工具方法实现2.1 单URL访问与解析代码实现代码说明2.2 示例调用

使用SpringBoot创建一个RESTful API的详细步骤

《使用SpringBoot创建一个RESTfulAPI的详细步骤》使用Java的SpringBoot创建RESTfulAPI可以满足多种开发场景,它提供了快速开发、易于配置、可扩展、可维护的优点,尤... 目录一、创建 Spring Boot 项目二、创建控制器类(Controller Class)三、运行

最好用的WPF加载动画功能

《最好用的WPF加载动画功能》当开发应用程序时,提供良好的用户体验(UX)是至关重要的,加载动画作为一种有效的沟通工具,它不仅能告知用户系统正在工作,还能够通过视觉上的吸引力来增强整体用户体验,本文给... 目录前言需求分析高级用法综合案例总结最后前言当开发应用程序时,提供良好的用户体验(UX)是至关重要

python实现自动登录12306自动抢票功能

《python实现自动登录12306自动抢票功能》随着互联网技术的发展,越来越多的人选择通过网络平台购票,特别是在中国,12306作为官方火车票预订平台,承担了巨大的访问量,对于热门线路或者节假日出行... 目录一、遇到的问题?二、改进三、进阶–展望总结一、遇到的问题?1.url-正确的表头:就是首先ur

手把手教你idea中创建一个javaweb(webapp)项目详细图文教程

《手把手教你idea中创建一个javaweb(webapp)项目详细图文教程》:本文主要介绍如何使用IntelliJIDEA创建一个Maven项目,并配置Tomcat服务器进行运行,过程包括创建... 1.启动idea2.创建项目模板点击项目-新建项目-选择maven,显示如下页面输入项目名称,选择

如何评价Ubuntu 24.04 LTS? Ubuntu 24.04 LTS新功能亮点和重要变化

《如何评价Ubuntu24.04LTS?Ubuntu24.04LTS新功能亮点和重要变化》Ubuntu24.04LTS即将发布,带来一系列提升用户体验的显著功能,本文深入探讨了该版本的亮... Ubuntu 24.04 LTS,代号 Noble NumBAT,正式发布下载!如果你在使用 Ubuntu 23.