天天看點

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

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

簡版(後面還有啰嗦版本​):

問題:

1、介紹RouteAttribute特性。

這個東西其實很簡單:主要用處就是設定路由罷了

什麼?不懂路由是什麼?

那麼你就了解為這是個位址就好了。

RouteAttribute 能簡寫成 Route

如下圖設定:

api/values/get

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

通路後的結果:

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

## 啰嗦版如下:

我們建立一個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)

我們可以看到下圖這樣的:

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

[RouteAttribute(“api/[controller]”)]

裡面有個被括号包含起來的: [controller]

這個controller在編譯後位址就是我們這個控制器的名字,他指向的路由就是:api/Values

就是以我們控制器的名字為準。

我們可以看到這個特性是在類上面的。如果我們要給某個方法設定路由也是可以的。

如下圖設定:

api/values/get

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

通路後的結果:

ll