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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值