使用ASP.NET Core探索最小的WebAPI

They are still working on the "dotnet new" templates, but you can also get cool templates from "yo aspnet" usingn Yeoman. The generator-aspnet package for Yeoman includes an empty web app, a console app, a few web app flavors, test projects, and a very simple Web API application that returns JSON and generally tries to be RESTful.

他们仍在使用“ dotnet new”模板,但您也可以使用Yeoman从“ yo aspnet”中获得很棒的模板。 Yeoman的generator-aspnet程序包包括一个空的Web应用程序,一个控制台应用程序,一些Web应用程序风格,测试项目以及一个非常简单的Web API应用程序,该应用程序返回JSON并通常尝试使用RESTful。

The startup.cs is pretty typical and basic. The Startup constructor sets up the Configuration with an appsettings.json file and add a basic Console logger. Then by calling "UseMvc()" we get to use all ASP.NET Core which includes both centralized routing and attribute routing. ASP.NET Core's controllers are unified now, so there isn't a "Controller" and "ApiController" base class. It's just Controller. Controllers that return JSON or those that return Views with HTML are the same so they get to share routes and lots of functionality.

startup.cs非常典型且基本。 启动构造函数使用appsettings.json文件设置配置,并添加基本的控制台记录器。 然后,通过调用“ UseMvc()”,我们可以使用所有ASP.NET Core,包括集中式路由和属性路由。 ASP.NET Core的控制器现已统一,因此没有“ Controller”和“ ApiController”基类。 只是控制器。 返回JSON的控制器或返回带有HTML的View的控制器是相同的,因此它们可以共享路由和许多功能。

public class Startup
{
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
}

public IConfigurationRoot Configuration { get; }

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddMvc();
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();

app.UseMvc();
}
}

Then you can make a basic controller and use Attribute Routing to do whatever makes you happy. Just by putting [HttpGet] on a method makes that method the /api/Values default for a simple GET.

然后,您可以制作一个基本的控制器,并使用“属性路由”执行任何使您满意的事情。 只需将[HttpGet]放在方法上,就可以使该方法成为简单GET的/ api / Values默认值。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;

namespace tinywebapi.Controllers
{
[Route("api/[controller]")]
public class ValuesController : Controller
{
// GET api/values
[HttpGet]
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}

// GET api/values/5
[HttpGet("{id}")]
public string Get(int id)
{
return "value";
}

// POST api/values
[HttpPost]
public void Post([FromBody]string value)
{
}

// PUT api/values/5
[HttpPut("{id}")]
public void Put(int id, [FromBody]string value)
{
}

// DELETE api/values/5
[HttpDelete("{id}")]
public void Delete(int id)
{
}
}
}

If we run this with "dotnet run" and call/curl/whatever to http://localhost:5000/api/Values we'd get a JSON array of two values by default. How would we (gasp!) add XML as a formatting/serialization option that would respond to a request with an Accept: application/xml header set?

如果我们使用“ dotnet run”来运行它,并调用/ curl /无论如何对http:// localhost:5000 / api / Values进行操作,则默认情况下,我们将获得两个值的JSON数组。 我们将如何(加倍!)将XML添加为一种格式设置/序列化选项,以使用Accept:application / xml标头集响应请求?

I'll add "Microsoft.AspNetCore.Mvc.Formatters.Xml" to project.json and then add one method to ConfigureServices():

我将“ Microsoft.AspNetCore.Mvc.Formatters.Xml”添加到project.json,然后向ConfigureServices()添加一种方法:

services.AddMvc()
        .AddXmlSerializerFormatters();

Now when I go into Postman (or curl, etc) and do a GET with Accept: application/xml as a header, I'll get the same object expressed as XML. If I ask for JSON, I'll get JSON.

现在,当我进入Postman(或curl等)并使用Accept:application / xml作为标题进行GET时,我将获得表示为XML的相同对象。 如果我要求JSON,我将获得JSON。

Postman is a great way to explore WebAPIs

If I like, I can create my own custom formatters and return whatever makes me happy. PDFs, vCards, even images.

如果愿意,我可以创建自己的自定义格式化程序并返回使我满意的任何内容。 PDF,vCard甚至图像。

Next post I'm going to explore the open source NancyFx framework and how to make minimal WebAPI using Nancy under .NET Core.

在下一篇文章中,我将探索开源NancyFx框架,以及如何在.NET Core下使用Nancy使WebAPI最小化。

翻译自: https://www.hanselman.com/blog/exploring-a-minimal-webapi-with-aspnet-core

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值