ASP.NET core webapi RouteAttribute _平台:windows (3)

简版(后面还有啰嗦版本​):

问题:
1、介绍RouteAttribute特性。
这个东西其实很简单:主要用处就是设置路由罢了
什么?不懂路由是什么?
那么你就理解为这是个地址就好了。

RouteAttribute 能简写成 Route

如下图设置:
api/values/get

ASP.NET core webapi RouteAttribute _平台:windows (3)_ll

访问后的结果:

ASP.NET core webapi RouteAttribute _平台:windows (3)_ll_02

ASP.NET core webapi RouteAttribute _平台:windows (3)_ll_03

## 啰嗦版如下:

我们创建一个webapi项目后,.netcore 会有根据模版生成一个默认的controllers这个文件夹,
该文件夹下有个文件 ValuesController.cs 如下代码所示 :

RouteAttribute 能简写成 Route

问题:
1、介绍RouteAttribute特性。

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

namespace mynetcorewebapi.Controllers
{
[RouteAttribute("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
// GET api/values
[HttpGet]
public ActionResult<IEnumerable<string>> Get()
{
return new string[] { "value1", "value2" };
}

// GET api/values/5
[HttpGet("{id}")]
public ActionResult<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)
{
}
}
}

RouteAttribute 这个特性是什么呢?

让我们跟踪一下代码:
我们可以看到他是我们程序集 Microsoft.AspNetCore.Mvc.Core 这个里面的某个方法。
这个方法的描述大概的介绍就是:
创建一个新路由模版给这个方法。
通俗点说:里面填写的就是我们的api地址

ASP.NET core webapi RouteAttribute _平台:windows (3)_ll_04

我们可以看到下图这样的:

ASP.NET core webapi RouteAttribute _平台:windows (3)_ll_05

[RouteAttribute(“api/[controller]”)]
里面有个被括号包含起来的: [controller]
这个controller在编译后地址就是我们这个控制器的名字,他指向的路由就是:api/Values
就是以我们控制器的名字为准。

我们可以看到这个特性是在类上面的。如果我们要给某个方法设定路由也是可以的。

如下图设置:
api/values/get

ASP.NET core webapi RouteAttribute _平台:windows (3)_ll_06

访问后的结果:

ASP.NET core webapi RouteAttribute _平台:windows (3)_ll_02

欢迎进qq群交流:704028989