一个ASP.NET-使用ASP.NET MVC 4 Beta和ASP.NET Web API制作JSON Web API

ASP.NET MVC 4 Beta came out last week. It's got lots of new features as well as some surprises that move us closer to the "One ASP.NET" idea. I talked about this a little in this week's MSDN Flash email newsletter (you can subscribe to MSDN Flash here; it's reasonably high signal, low noise). Here's part of what I said:

ASP.NET MVC 4 Beta上周发布。 它具有许多新功能以及一些使我们更接近“一个ASP.NET”概念的惊喜。 我在本周的MSDN Flash电子邮件时事通讯中谈到了这一点(您可以在此处订阅MSDN Flash ;这是合理的高信号,低噪声)。 这是我说的部分内容

Don't think of ASP.NET as an island. It's a citizen of the larger community. More and more of ASP.NET is open source, and we push hard every day to stay open and be open. We want to make ASP.NET more pluggable, more open, more fun. We've got big things planned - some that will surprise you. I hope you'll join the conversation and the community.

不要将ASP.NET视为孤岛。 它是更大社区的公民。 越来越多的ASP.NET是开源的,我们每天都在努力保持开放和开放。 我们希望使ASP.NET更可插入,更开放,更有趣。 我们已计划了大事-有些会让您感到惊讶的。 希望您能加入对话和社区。

Here's some of the stuff that's been improved in MVC 4.

这是MVC 4中已改进的一些内容。

Beta中的新功能 (New Features in the Beta)

  • ASP.NET Web API

    ASP.NET Web API
  • Refreshed and modernized default project templates

    刷新和现代化的默认项目模板
  • New mobile project template

    新的移动项目模板
  • Many new features to support mobile apps

    支持移动应用程序的许多新功能
  • Recipes to customize code generation

    定制代码生成的食谱
  • Enhanced support for asynchronous methods

    增强了对异步方法的支持
  • Read the full feature list in the release notes

    阅读发行说明中的完整功能列表

You may have heard me talking about LEGO in the past, and showing how you can fit things together better with NuGet. I've mentioned One ASP.NET in the context of the new features in Web Forms as well. Here's a diagram I've shown internally a few times. We'll keep adding more information about how these fit together and what you can build with them on http://asp.net/vnext.

您可能听说过我过去谈论乐高,并展示了如何通过NuGet更好地将事物组合在一起。 在Web窗体的新功能中我也提到了一个ASP.NET 。 这是我在内部显示过几次的图表。 我们将继续在http://asp.net/vnext上添加有关它们如何组合以及如何使用它们构建的更多信息。

All the parts of ASP.NET, all the subsystems are all part of the larger ASP.NET community

In fact, in the interest of focusing on One ASP.NET, the "WCF Web API" is now ASP.NET Web API and it comes with ASP.NET MVC now. Even though it ships with MVC 4 Beta today, don't let that take away from the One ASP.NET vision. You can use Web API in ASP.NET Web Forms no problem. That's kind of the point. ;)

实际上,为了专注于一个ASP.NET,“ WCF Web API”现在是ASP.NET Web API,并且现在随ASP.NET MVC一起提供。 即使它随MVC 4 Beta一起提供,也不要让它脱离One ASP.NET的构想。 您可以在ASP.NET Web窗体中使用Web API没问题。 这就是重点。 ;)

为什么要使用Web API? (Why do you want a Web API?)

If your app - your business's data model - has an API, then suddenly your Web API is opened up to native apps, iPhone apps, Windows 8 apps, whatever, apps. It's Web Services. Remember those?

如果您的应用程序(您企业的数据模型)具有API,那么您的Web API就会突然向本机应用程序,iPhone应用程序,Windows 8应用程序以及任何其他应用程序开放。 它是Web服务。 还记得那些吗?

I can use XML or JSON or something else with my API. JSON is nice for mobile apps with slow connections, for example. You can call an API from jQuery and better utilize the client's machine and browser. You can make a Gmail type single page, or a hybrid; it's up to you.

我可以在我的API中使用XML或JSON或其他内容。 例如,JSON适用于连接速度慢的移动应用程序。 您可以从jQuery调用API,并更好地利用客户端的计算机和浏览器。 您可以将Gmail类型设置为单页或混合页; 由你决定。

一切如何融入一个ASP.NET (How it all fits into One ASP.NET)

The idea behind One ASP.NET is that I want folks to be able to make apps that have real-time components with SignalR, clean, simple APIs with Web API, all in one pages with KnockoutJS, pages with MVC, Web Forms or Web Pages, as well as existing ASP.NET systems like OData, ASMX, and more. I want open source projects like JSON.NET, KnockoutJS, SignalR, Backbone, MongoDB, Scaffolding, NHIbernate, Ninject (and the list goes on) to all play in the same ASP.NET LEGO sandbox. We'll put all these subcomponents on NuGet and they'll live alongside community components and you'll be able to build ASP.NET applications starting from some base template and add just the pieces you want. We are getting there. I want folks to use the parts they want, and swap out the parts they don't. Everything should work together. I've always said I want to open source everything we can as fast as Microsoft can take it, and I'll keep pushing if it kills me my boss.

一个ASP.NET背后的想法是,我希望人们能够制作具有SignalR实时组件,具有Web API的干净,简单API,包含KnockoutJS,包含MVC,Web Forms或Web的页面的实时应用程序。页面以及现有的ASP.NET系统(如OData,ASMX等)。 我希望像JSON.NET,KnockoutJS,SignalR,Backbone, MongoDB ,Scaffolding,NHIbernate,Ninject这样的开源项目都可以在同一ASP.NET LEGO沙箱中播放。 我们会将所有这些子组件放在NuGet上,并将它们与社区组件一起使用,并且您将能够从一些基本模板开始构建ASP.NET应用程序,并仅添加所需的部分。 我们到了那里。 我希望人们使用他们想要的部分,并交换他们不需要的部分。 一切都应该一起工作。 我一直说我想尽可能快地开源所有源代码,如果微软杀死 我的老板,我会继续努力。

不推特 (NotTwitter)

Lemme make a NotTwitter app real quick. Here's a quick model:

Lemme可以快速制作出NotTwitter应用。 这是一个快速的模型:

public class NotATweet
{
public int ID { get; set; }
public string Username { get; set; }
public string Text { get; set; }
public DateTime Published { get; set; }
}

I'll use the default scaffolding to get the UI, but then I'll install the MvcScaffolding extra NuGet package and scaffold it using a Repository pattern.

我将使用默认的脚手架来获取UI,但随后我将安装MvcScaffolding额外的NuGet程序包并使用存储库模式来脚手架。

PS>Scaffold -ModelType NotATweet -DbContext NotTwitterContext -Scaffolder Repository -Force 

Then I'll scaffold a controller that uses this Repo (you can do this from the UI or from the NuGet package console):

然后,我将搭建一个使用此Repo的控制器(您可以从UI或NuGet程序包控制台执行此操作):

Scaffold -Controller NotATwitter -ModelType NotATweet -DbContext NotTwitterContext -Scaffolder MvcScaffolding.Controller -Repository

And here's the resulting Scaffolded UI.

这是生成的脚手架UI。

It's Not Twitter

The controller for my pages is standard fare. Now I'll add one via Add Controller to make an API for my NotTwitter application.

我页面的控制器是标准票价。 现在,我将通过“添加控制器”添加一个,为我的NotTwitter应用程序创建一个API。

I'll change my route to make /api go to my app's API controller;

我将更改路由,使/ api转到应用程序的API控制器;

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

Here's my Web API controller code. A few things to notice. I'm talking to the same IRepository that the page controller uses. I'm returning HTTP Status Codes that are appropriate for each response. See how after the Create (where I POST a JSON representation of NotATweet) that I return HttpStatusCode.Created 201 and set the header's location to include the location of the new resource?

这是我的Web API控制器代码。 一些注意事项。 我正在与页面控制器使用的同一IRepository进行交谈。 我正在返回适合每个响应的HTTP状态代码。 看看在创建之后(我在其中发布NotATweet的JSON表示形式)之后,我如何返回HttpStatusCode.Created 201并设置标头的位置以包括新资源的位置?

public class NotATwitterAPIController : ApiController
{
private readonly INotATweetRepository notatweetRepository;
    public NotATwitterAPIController(INotATweetRepository notatweetRepository)
{
this.notatweetRepository = notatweetRepository;
}

// GET /api/notatwitterapi
public IQueryable<NotATweet> Get()
{
return notatweetRepository.All;
}

// GET /api/notatwitterapi/5
public NotATweet Get(int id)
{
var notatweet = notatweetRepository.Find(id);
if (notatweet == null)
throw new HttpResponseException(HttpStatusCode.NotFound);
return notatweet;
}

// POST /api/notatwitterapi
public HttpResponseMessage<NotATweet> Post(NotATweet value)
{
if (ModelState.IsValid)
{
notatweetRepository.InsertOrUpdate(value);
notatweetRepository.Save();

//Created!
var response = new HttpResponseMessage<NotATweet>(value, HttpStatusCode.Created);

//Let them know where the new NotATweet is
string uri = Url.Route(null, new { id = value.ID });
response.Headers.Location = new Uri(Request.RequestUri, uri);

return response;

}
throw new HttpResponseException(HttpStatusCode.BadRequest);
}

// PUT /api/notatwitterapi/5
public HttpResponseMessage Put(int id, NotATweet value)
{
if (ModelState.IsValid)
{
notatweetRepository.InsertOrUpdate(value);
notatweetRepository.Save();
return new HttpResponseMessage(HttpStatusCode.NoContent);
}
throw new HttpResponseException(HttpStatusCode.BadRequest);
}

// DELETE /api/notatwitterapi/5
public void Delete(int id)
{
var notatweet = notatweetRepository.Find(id);
if (notatweet == null)
throw new HttpResponseException(HttpStatusCode.NotFound);

notatweetRepository.Delete(id);
}
}

Then I'll hit /api with Fiddler. Notice how JSON popped out the other end?

然后,我用Fiddler击打/ api。 请注意,JSON是如何从另一端弹出的?

I'll change the accept header to Accept: application/xml and xml pops out. You can plug in your own and make Web API spit out iCal or whatever you like. You can make media formatters or even plug in others for the defaults. For example, here's a JSON.NET Formatter for Web API.

我将accept标头更改为Accept:application / xml并弹出xml。 您可以插入自己的插件,并使Web API吐出iCal或您喜欢的任何东西。 您可以制作媒体格式化程序,甚至可以插入其他媒体格式化程序作为默认设置。 例如,这是Web APIJSON.NET格式化程序

Now can we make NotTweets? You can use tools like the JSON Formatter to handcraft JSON for testing. Now I'll POST a Json serialized NotTweet:

现在我们可以制作NotTweets了吗? 您可以使用JSON Formatter之类的工具来手工制作JSON以进行测试。 现在,我将发布一个Json序列化的NotTweet:

Notice that the result is an HTTP 201 Created. If I then GET /api, I can see it's there:

请注意,结果是HTTP 201 Created。 如果再获取GET / api,则可以看到它:

I can also affect things with the URL and query strings like this GET /api?$orderby=Username HTTP/1.1 so I can so query composition without totally buying into OData-style URLs if I don't want to.

我还可以使用URL和查询字符串来影响事物,例如GET / api?$ orderby = Username HTTP / 1.1,这样我就可以查询组成而不必完全购买OData样式的URL。

As I mentioned, I can use XML or JSON or something else with my API. JSON is good for mobile apps with slow connections, for example. You can call this API from jQuery and better utilize the client's machine and browser.

如前所述,我可以在API中使用XML或JSON或其他内容。 例如,JSON适用于连接速度较慢的移动应用程序。 您可以从jQuery调用此API,以更好地利用客户端的计算机和浏览器。

There's also the "calling" side of this, which is HttpClient. You can call out to other APIs like Twitter and authenticate using OAuth. Other people might call your API from the client side using jQuery and Javascript or from the server side using HttpClient.

还有一个“调用”方面,即HttpClient。 您可以调出Twitter等其他API并使用OAuth进行身份验证。 其他人可能使用jQuery和Javascript客户端调用您的API,或者使用HttpClient从服务器端调用您的API。

Web API has many more possibilities than this example. Spend some time on Henrik's blog (he helped invent HTTP! Listen to him on his episode of the Hanselminutes Podcast)

Web API具有比本示例更多的可能性。 花一些时间在Henrik的博客上(他帮助发明了HTTP!在Hanselminutes播客的一集中请听听他的话)

We've got a new section up on the ASP.NET site http://asp.net/web-api with a lot of info. Here's some resources for easily adding an API to your app. You can even self-host your own Web API without IIS in a service or other application!

我们在ASP.NET网站http://asp.net/web-api上增加了一个新部分,其中包含很多信息。 这里有一些资源,可以轻松地向您的应用添加API。 您甚至可以在服务或其他应用程序中自托管您自己的Web API,而无需IIS

相关链接 (Related Links)

翻译自: https://www.hanselman.com/blog/one-aspnet-making-json-web-apis-with-aspnet-mvc-4-beta-and-aspnet-web-api

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值