濡備綍鍦?Core Web API 涓互涓夌鏂瑰紡杩斿洖鏁版嵁

Posted 涓€绾跨爜鍐?,

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了濡備綍鍦?Core Web API 涓互涓夌鏂瑰紡杩斿洖鏁版嵁相关的知识,希望对你有一定的参考价值。

鍦?ASP.NET Core 涓湁涓夌杩斿洖 鏁版嵁 鍜?HTTP鐘舵€佺爜 鐨勬柟寮忥紝鏈€绠€鍗曠殑灏辨槸鐩存帴杩斿洖鎸囧畾鐨勭被鍨嬪疄渚嬶紝濡備笅浠g爜鎵€绀猴細


    [ApiController]
    [Route("[controller]")]
    public class WeatherForecastController : ControllerBase
    {
        [HttpGet]
        public IEnumerable<WeatherForecast> Get()
        {
            var rng = new Random();
            return Enumerable.Range(1, 5).Select(index => new WeatherForecast
            {
                Date = DateTime.Now.AddDays(index),
                TemperatureC = rng.Next(-20, 55),
                Summary = Summaries[rng.Next(Summaries.Length)]
            })
            .ToArray();
        }
    }

闄や簡杩欑锛屼篃鍙互杩斿洖 IActionResult 瀹炰緥 鍜? ActionResult <T> 瀹炰緥銆?/p>

铏界劧杩斿洖鎸囧畾鐨勭被鍨?鏄渶绠€鍗曠矖鏆寸殑锛屼絾瀹冨彧鑳借繑鍥炴暟鎹紝闄勫甫涓嶄簡http鐘舵€佺爜锛岃€?IActionResult 瀹炰緥鍙互灏?鏁版嵁 + Http鐘舵€佺爜 涓€鍚屽甫缁欏墠绔紝鏈€鍚庡氨鏄?ActionResult<T> 瀹冨皝瑁呬簡鍓嶉潰涓よ€咃紝鍙互瀹炵幇涓ょ妯″紡鐨勮嚜鐢卞垏鎹紝馃悅鍚с€?/p>

鎺ヤ笅鏉ヤ竴璧疯璁轰笅濡備綍鍦?ASP.NET Core Web API 涓娇鐢ㄨ繖涓夌鏂瑰紡銆?/p>

鍒涘缓 Controller 鍜?Model 绫?/h2>

鍦ㄩ」鐩殑 Models 鏂囦欢澶逛笅鏂板缓涓€涓?Author 绫伙紝浠g爜濡備笅锛?/p>


    public class Author
    {
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }

鏈変簡杩欎釜 Author 绫伙紝鎺ヤ笅鏉ュ垱寤轰竴涓?DefaultController 绫汇€?/p>


using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;

namespace IDGCoreWebAPI.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class DefaultController : ControllerBase
    {
        private readonly List<Author> authors = new List<Author>();
        public DefaultController()
        {
            authors.Add(new Author()
            {
                Id = 1,
                FirstName = "Joydip",
                LastName = "Kanjilal"
            });
            authors.Add(new Author()
            {
                Id = 2,
                FirstName = "Steve",
                LastName = "Smith"
            });
        }

        [HttpGet]
        public IEnumerable<Author> Get()
        {
            return authors;
        }

        [HttpGet("{id}", Name = "Get")]
        public Author Get(int id)
        {
            return authors.Find(x => x.Id == id);
        }
    }
}

鍦?Action 涓繑鍥?鎸囧畾绫诲瀷

鏈€绠€鍗曠殑鏂瑰紡灏辨槸鍦?Action 涓洿鎺ヨ繑鍥炰竴涓?绠€鍗曠被鍨?鎴栬€?澶嶆潅绫诲瀷锛屽叾瀹炲湪涓婇潰鐨勪唬鐮佹竻鍗曚腑锛屽彲浠ョ湅鍒?Get 鏂规硶杩斿洖浜嗕竴涓?authors 闆嗗悎锛岀湅娓呮浜嗭紝杩欎釜鏂规硶瀹氫箟鐨勬槸 IEnumerable<Author>銆?/p>


[HttpGet]
public IEnumerable<Author> Get()
{
   return authors;
}

鍦?ASP.NET Core 3.0 寮€濮嬶紝浣犱笉浠呭彲浠ュ畾涔夊悓姝ュ舰寮忕殑 IEnumerable<Author>鏂规硶锛屼篃鍙互瀹氫箟寮傛褰㈠紡鐨?IAsyncEnumerable<T>鏂规硶锛屽悗鑰呯殑涓嶅悓鐐瑰湪浜庡畠鏄竴涓紓姝ユā寮忕殑闆嗗悎锛屽ソ澶勫氨鏄?涓嶉樆濉?/code> 褰撳墠鐨勮皟鐢ㄧ嚎绋嬶紝鍏充簬 IAsyncEnumerable<T> 鏇村鐨勭煡璇嗭紝鎴戜細鍦ㄥ悗闈㈢殑鏂囩珷涓拰澶у鍒嗕韩銆?/p>

涓嬮潰鐨勪唬鐮佸睍绀轰簡濡備綍鐢?寮傛闆嗗悎 鏉ユ敼閫?Get 鏂规硶銆?/p>


[HttpGet]
public async IAsyncEnumerable<Author> Get()
{
   var authors = await GetAuthors();
   await foreach (var author in authors)
   {
        yield return author;
   }
}

鍦?Action 涓繑鍥?IActionResult 瀹炰緥

濡傛灉浣犺杩斿洖 data + httpcode 鐨勫弻閲嶉渶姹傦紝閭d箞 IActionResult 灏辨槸浣犺鎵剧殑涓滆タ锛屼笅闈㈢殑浠g爜鐗囨灞曠ず浜嗗浣曞幓瀹炵幇銆?/p>


[HttpGet]
public IActionResult Get()
{
  if (authors == null)
      return NotFound("No records");

  return Ok(authors);
}

涓婇潰鐨勪唬鐮佹湁 Ok锛?code>NotFound 涓や釜鏂规硶锛屽搴旂潃 OKResult锛孨otFoundResult锛?Http Code 瀵瑰簲鐫€ 200锛?04銆傚綋鐒惰繕鏈夊叾浠栫殑濡傦細CreatedResult, NoContentResult, BadRequestResult, UnauthorizedResult, 鍜?UnsupportedMediaTypeResult锛岄兘鏄?IActionResult 鐨勫瓙绫汇€?/p>

鍦?Action 涓繑鍥?ActionResult<T> 瀹炰緥

ActionResult<T> 鏄湪 ASP.NET Core 2.1 涓寮曞叆鐨勶紝瀹冪殑浣滅敤灏辨槸鍖呰浜嗗墠闈㈣繖绉嶆ā寮忥紝鎬庝箞鐞嗚В鍛紵 灏辨槸鍗冲彲浠ヨ繑鍥?IActionResult 锛屼篃鍙互杩斿洖鎸囧畾绫诲瀷锛屼粠 ActionResult<TValue> 绫讳笅鐨勪袱涓瀯閫犲嚱鏁颁腑灏卞彲浠ョ湅鐨勫嚭鏉ャ€?/p>


public sealed class ActionResult<TValue> : IConvertToActionResult
{
    public ActionResult Result  {get;}

    public TValue Value  {get;}

    public ActionResult(TValue value)
    {
        if (typeof(IActionResult).IsAssignableFrom(typeof(TValue)))
        {
            throw new ArgumentException(Resources.FormatInvalidTypeTForActionResultOfT(typeof(TValue), "ActionResult<T>"));
        }
        Value = value;
    }

    public ActionResult(ActionResult result)
    {
        if (typeof(IActionResult).IsAssignableFrom(typeof(TValue)))
        {
            throw new ArgumentException(Resources.FormatInvalidTypeTForActionResultOfT(typeof(TValue), "ActionResult<T>"));
        }
        Result = (result ?? throw new ArgumentNullException("result"));
    }
}

鏈変簡杩欎釜鍩虹锛屾帴涓嬫潵鐪嬬湅濡備綍鍦?Action 鏂规硶涓幓鎺ヨ繖涓ょ绫诲瀷銆?/p>


[HttpGet]
public ActionResult<IEnumerable<Author>> Get()
{
  if (authors == null)
       return NotFound("No records");
   return authors;
}

鍜屾枃绔犱箣鍓嶇殑 Get 鏂规硶鐩告瘮锛岃繖閲岀洿鎺ヨ繑鍥?authors 鑰屼笉闇€瑕佸啀鐢?OK(authors) 鍖呰锛屾槸涓嶆槸涓€涓潪甯稿ソ鐨勭畝鍖栧憿锛?鎺ヤ笅鏉ュ啀鎶?Get 鏂规硶寮傛鍖栵紝棣栧厛鑰冭檻涓嬮潰杩斿洖 authors 闆嗗悎鐨勫紓姝ユ柟娉曘€?/p>


private async Task<List<Author>> GetAuthors()
{
    await Task.Delay(100).ConfigureAwait(false);
    return authors;
}

鍊煎緱娉ㄦ剰鐨勬槸锛屽紓姝ユ柟娉曞繀椤昏鏈夎嚦灏戜竴涓?await 璇彞锛屽鏋滀笉杩欐牱鍋氱殑璇濓紝缂栬瘧鍣ㄤ細鎻愮ず涓€涓鍛婇敊璇紝鍛婄煡浣犺繖涓柟娉曞皢浼氳 鍚屾鎵ц锛屼负浜嗛伩鍏嶅嚭鐜拌繖绉嶅按灏紝鎴戝湪 Task.Delay 涓婂仛浜嗕竴涓?await銆?/p>

涓嬮潰灏辨槸鏇存柊鍚庣殑 Get 鏂规硶锛屾敞鎰忎竴涓嬭繖閲屾垜鐢ㄤ簡 await 鍘昏皟鐢ㄥ垰鎵嶅垱寤虹殑寮傛鏂规硶锛屼唬鐮佸弬鑰冨涓嬨€?/p>


[HttpGet]
public async Task<ActionResult<IEnumerable<Author>>> Get()
{
   var data = await GetAuthors();
   if (data == null)
        return NotFound("No record");
   return data;
}

濡傛灉浣犳湁涓€浜涘畾鍒跺寲闇€姹傦紝鍙互瀹炵幇涓€涓嚜瀹氫箟鐨?ActionResult 绫伙紝鍋氭硶灏辨槸瀹炵幇 IActionResult 涓殑 ExecuteResultAsync 鏂规硶鍗冲彲銆?/p>

璇戞枃閾炬帴锛?a href="https://link.segmentfault.com/?enc=1UWe4cN%2BpIH4QSXbWZz%2Ftg%3D%3D.DWWYpyrEfaK0O7ibnqAUBYsP8R8j9bC7spmq%2BmzYzYGR5e4e19m%2B8iDgt97KrtS8BsHQvUTfQ7BvQJXEs63HC6qWncdtmKFIf3tepR%2ButX6NPCfo1yj6qsd3q642sVze" rel="nofollow">https://www.infoworld.com/art...

鏇村楂樿川閲忓共璐э細鍙傝鎴戠殑 GitHub: csharptranslate

以上是关于濡備綍鍦?Core Web API 涓互涓夌鏂瑰紡杩斿洖鏁版嵁的主要内容,如果未能解决你的问题,请参考以下文章

濡備綍鍦ㄧ▼搴忓憳闈㈣瘯涓劚棰栬€屽嚭

濡備綍鍦?CentOS 8 涓婂畨瑁匤enkins

濡備綍鍦╳indows10涓婇潰杩愯HyperLedger Fabric1.4

濡備綍鍦║BUNTU 20.04鎿嶄綔绯荤粺涓婃坊鍔爏wap浜ゆ崲绌洪棿

濡備綍鍦ㄤ娇鐢╒ue鐨勬儏鍐典笅瀹炵幇Electron鎵撳紑鏂囦欢淇濆瓨瀵硅瘽妗嗭紵

濡備綍灏嗘暟鎹粠MySQL/MongoDB涓縼绉昏嚦浜戝紑鍙戞暟鎹簱