最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

ASP.NET?Core之Web?API介紹

 更新時(shí)間:2022年04月15日 07:47:47   作者:Ruby_Lu  
這篇文章介紹了ASP.NET?Core?Web?API,對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧

1.簡(jiǎn)單介紹

ASP.NET Core Web API 是 ASP.NET Core MVC 的一個(gè)功能。ASP.NET Core MVC 包含了對(duì) Web API 的支持??梢詷?gòu)建多種客戶端的 HTTP 服務(wù)。ASP.NET Core Web API可用于在 .NET Core 上構(gòu)建 RESTful 應(yīng)用程序。

框架包含對(duì) HTTP 內(nèi)容協(xié)商的支持,內(nèi)置支持以 JSON 或 XML 格式化的數(shù)據(jù)。編寫自定義格式化程序已添加對(duì)自有格式的支持。

使用鏈接生成對(duì)超媒體的支持。啟用對(duì)跨資源共享(CORS)的支持,以便 Web API 可以在多個(gè) Web應(yīng)用程序之間共享。

例如,新建一個(gè) API 項(xiàng)目,默認(rèn)包含一個(gè) ValuesController:

[Route("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)
        {
        }
    }

默認(rèn)包含了 GET,POST,PUT,DELETE 這幾個(gè) HTTP 請(qǐng)求操作。這里直接使用特性路由,在控制器上注明 [Route("api/[controller]")]。調(diào)試并打開瀏覽器輸入 https://localhost:5000/api/values ,會(huì)返回?cái)?shù)據(jù)。

2.自定義格式化(Format)

ASP.NET Core MVC內(nèi)建支持對(duì)相應(yīng)數(shù)據(jù)的格式,用來(lái)修正格式或生成客戶端指定的格式。

1.特定格式的操作結(jié)果

某些操作結(jié)果的類型是特定的格式,比如 JsonResult 或 ContentResult 。操作可以總是返回格式為特定格式的具體結(jié)果。比如返回 JsonResult 時(shí)將返回 JSON 格式化數(shù)據(jù),而不管客戶端要求的是什么格式。

操作并不要求返回任何特定的類型, MVC 支持任何對(duì)象作為返回值。如果操作返回的是 IActionResult 的某個(gè)實(shí)現(xiàn),并且控制器繼承自 Controller ,那么可以使用更多輔助方法。如果不是,則將使用合適的 IOutputFormatter 實(shí)現(xiàn)序列化對(duì)象。

若要從繼承 Controller 基類的控制器返回特定格式的數(shù)據(jù),可以使用內(nèi)置的輔助方法 Json 來(lái)返回 JSON 格式, 使用 Content 來(lái)返回 純文本。操作方法的返回類型必須是指定的結(jié)果類型(如 JsonResult)或 IActionResult。

[HttpGet]
        public JsonResult Get()
        {
            return Json(new User());
        }

以上代碼 Content-Type 將返回 application/json。

要想返回純文本格式的數(shù)據(jù),則使用 ContentResult 以及 Content 輔助方法:

[HttpGet]
        public ContentResult Get()
        {
            return Content("result");
        }

以上代碼 Content-Type 將返回  test/plan 。 也可以使用一個(gè)字符串相應(yīng)類型來(lái)實(shí)現(xiàn)這個(gè)行為:

[HttpGet]
        public string Get()
        {
            return "result";
        }

對(duì)于具有多個(gè)返回類型或選項(xiàng)的復(fù)雜操作,請(qǐng)選擇 IActionResult 作為返回類型。

2.配置格式化程序

如果應(yīng)用程序想支持默認(rèn) JSON 之外的格式,可以在 project.json 文件中添加這些額外的依賴項(xiàng),并配置 MVC 來(lái)支持。輸入和輸出的格式是可以隔離的。輸入格式通過(guò)使用模型綁定,輸出格式通過(guò)格式化響應(yīng)。

3.添加對(duì) XML 格式的支持

要添加對(duì) XML 格式的支持,需要先安裝 Microsoft.AspNetCore.Mvc.Formatters.Xml 包,然后在 ConfigureServices 中配置 XmlSerializerFormatters :

services.AddMvc()
                .AddXmlSerializerFormatters()
                .SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

或者可以只添加輸出格式:

services.AddMvc(options => {
                options.OutputFormatters.Add(new XmlSerializerOutputFormatter());
            })
                //.AddXmlSerializerFormatters()
                .SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

這兩種方法都將使用 System.Xml.Serialization.XmlSerializer 序列化結(jié)果。還可以通過(guò)添加其他相關(guān)格式來(lái)使用 System.Runtime.Serialization.DataContractSerializer :

services.AddMvc(options => {
                options.OutputFormatters.Add(new XmlDataContractSerializerOutputFormatter());
            })
                //.AddXmlSerializerFormatters()
                .SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

4.強(qiáng)制特定格式化

若是想為某個(gè)操作限制響應(yīng)格式,則可以使用 [Produces] 過(guò)濾器。[Produces] 過(guò)濾器可以為這個(gè)控制器或 Action 指定響應(yīng)格式:

[HttpGet("{id}", Name = "Get")]
        [Produces("application/json")]
        public string Get(int id)
        {
            return "value";
        }

對(duì)于一些特殊情況,可能不想使用內(nèi)建的格式化實(shí)現(xiàn)。默認(rèn)情況下,返回類型為 string 時(shí)將格式化為 text/plain 。這種行為可以通過(guò)移除 TextOutputFormatter 來(lái)改變:

public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc(options => {
                options.OutputFormatters.RemoveType<TextOutputFormatter>();
                options.OutputFormatters.RemoveType<HttpNoContentOutputFormatter>();
            }).SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        }

上面移除了 TextOutputFormatter 和 HttpNoContentOutputFormatter,當(dāng)返回類型為 string 時(shí),將返回 406 Not Acceptable。如果存在 XML 格式化程序,則將格式化響應(yīng)結(jié)果。

移除了 HttpNoContentOutputFormatter ,當(dāng)返回某個(gè)返回類型為模型對(duì)象的操作返回 null 時(shí),將返回 204 No Content 響應(yīng)。JSON 格式將簡(jiǎn)單地返回主體信息為 null 的響應(yīng),而 XML 格式將返回一個(gè)空的帶有 xsi:nil="true" 屬性的 XML 元素。

5.響應(yīng)格式 URL 映射

客戶端可以在 URL 中請(qǐng)求特定的格式,比如在請(qǐng)求字符串或路徑中,或者通過(guò)使用特定格式的文件擴(kuò)展名(比如 .xml 或 .json),需要在 API 所使用的路由中指定:

[FormatFilter]
    public class UserController : Controller
    {
        // GET: api/User
        [HttpGet]
        [Route("[controller]/[action]/{id}.{format?}")]
        public IActionResult GetById(int id)
        {
            return Content("xxx");
        }
}

這個(gè)路由配置將允許使用可選的文件擴(kuò)展名來(lái)指定格式。[FormatFilter] 特性將在 RouteData 中檢查該格式的值是否存在,并創(chuàng)建響應(yīng)時(shí)將響應(yīng)數(shù)據(jù)映射到相應(yīng)的格式:

RouteFormatter

/User/GetById/5 :默認(rèn)輸出格式

/User/GetById/5.json :JSON格式(如果配置過(guò))

/User/GetById/5.xml; :XML格式(如果配置過(guò))

6.自定義格式化程序 Protocol Buffers (簡(jiǎn)稱 protobuf)

Protocol Buffers 是一種輕便高效的結(jié)構(gòu)化數(shù)據(jù)存儲(chǔ)格式,可用于結(jié)構(gòu)化數(shù)據(jù)串行化,或者說(shuō)序列化。它很適合做數(shù)據(jù)存儲(chǔ)或 RPC(遠(yuǎn)程過(guò)程調(diào)用協(xié)議)數(shù)據(jù)交換格式??捎糜谕ㄓ崊f(xié)議,數(shù)據(jù)存儲(chǔ)等領(lǐng)域的語(yǔ)言無(wú)關(guān),平臺(tái)無(wú)關(guān),可擴(kuò)展的序列化結(jié)構(gòu)數(shù)據(jù)格式。比如實(shí)現(xiàn)一個(gè)程序返回 protobuf 格式:

創(chuàng)建 API 項(xiàng)目,添加 protobuf-net 引用。

添加 ProtobufFormatter 類:

public class ProtobufFormatter:OutputFormatter
    {
        public string ContentType { get; private set; }
        public ProtobufFormatter()
        {
            ContentType = "application/proto";
            SupportedMediaTypes.Add(MediaTypeHeaderValue.Parse("application/proto"));
        }

        public override Task WriteResponseBodyAsync(OutputFormatterWriteContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }
            var response = context.HttpContext.Response;
            Serializer.Serialize(response.Body,context.Object);
            return Task.FromResult(0);
        }

    }

繼承 OutputFormatter ,然后實(shí)現(xiàn) WriteResponseBodyAsync 方法,初始化時(shí)賦值 ContentType ,并添加支持 MediaType。在 WriteResponseBodyAsync 方法中獲取 Response ,調(diào)用 protobuf-net 的 Serializer.Serialize 方法將 Object 序列化至輸出內(nèi)容。 protobuf 在序列化時(shí)必須指定順序,添加 User 類,實(shí)現(xiàn) protobuf 實(shí)體:

[ProtoContract]
    public class User
    {
        [ProtoMember(1)]
        public int Id { get; set; }
        [ProtoMember(2)]
        public string Name { get; set; }
        [ProtoMember(3)]
        public int Age { get; set; }
    }

類上需要添加 [ProtoContract] 特性,字段上需要 ProtoMember 特性,并指定順序。然后修改 UserController:

[Route("api/[controller]")]
    [ApiController]
    [FormatFilter]
    public class UserController : Controller
    {
        private IEnumerable<User> users;
        public UserController()
        {
            users = new User[] {
                new User(){ Id=1,Name="Bob",Age = 20},
                new User(){ Id=2,Name="Tom",Age = 22}
            };
        }
        // GET: api/User
        [HttpGet]
        [Produces("application/proto")]
        public IEnumerable<User> Get()
        {
            return users;
        }
}

修改 ConfigureServices :

public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc(options => {
                options.OutputFormatters.Add(new ProtobufFormatter());
            }).SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        }

運(yùn)行程序,會(huì)返回一個(gè)二進(jìn)制文件。

創(chuàng)建一個(gè)控制臺(tái),檢查序列化:

class Program
    {
        static void Main(string[] args)
        {
            HttpClient client = new HttpClient();
            var stream = client.GetStreamAsync("https://localhost:44358/api/User").Result;
            var users = Serializer.Deserialize<List<User>>(stream);
            foreach (var user in users)
            {
                Console.WriteLine($"Id:{user.Id} - Name:{user.Name} - Age:{user.Age}");
            }
            Console.ReadKey();
        }
    }

到此這篇關(guān)于ASP.NET Core Web API的文章就介紹到這了。希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • .net6引入autofac框架

    .net6引入autofac框架

    這篇文章介紹了.net6引入autofac框架的方法,文中通過(guò)示例代碼介紹的非常詳細(xì)。對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2021-12-12
  • System.Diagnostics.Metrics .NET 6 全新指標(biāo)API講解

    System.Diagnostics.Metrics .NET 6 全新指標(biāo)API講解

    本文詳細(xì)講解了.NET 6全新指標(biāo)System.Diagnostics.Metrics,文中通過(guò)示例代碼介紹的非常詳細(xì)。對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2021-11-11
  • ASP.NET 中的Application詳解

    ASP.NET 中的Application詳解

    Application對(duì)象是HttpApplicationState類的一個(gè)實(shí)例,Application狀態(tài)是整個(gè)應(yīng)用程序全局的。本文主要詳細(xì)介紹Application對(duì)象的用法。
    2016-04-04
  • SQL Server 2005 RTM 安裝錯(cuò)誤 :The SQL Server System Configuration Checker cannot be executed due to

    SQL Server 2005 RTM 安裝錯(cuò)誤 :The SQL Server System Configuratio

    SQL Server 2005 RTM 安裝錯(cuò)誤 :The SQL Server System Configuration Checker cannot be executed due to...
    2007-02-02
  • 詳解Asp.net 5中的ApplicationBuilder

    詳解Asp.net 5中的ApplicationBuilder

    這篇文章介紹了Asp.net 5中的ApplicationBuilder,文中通過(guò)示例代碼介紹的非常詳細(xì)。對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2022-01-01
  • ASP.NET DropDownList控件的使用方法

    ASP.NET DropDownList控件的使用方法

    ASP.NET DropDownList控件的使用方法,學(xué)習(xí)asp.net的朋友沒(méi)用過(guò)這個(gè)控件的朋友可以參考下。
    2010-04-04
  • .NET中開源文檔操作組件DocX的介紹與使用

    .NET中開源文檔操作組件DocX的介紹與使用

    在大家日常開發(fā)中讀寫Offic格式的文檔,大家多少都有用到,可能方法也很多,組件有很多。這里不去討論其他方法的優(yōu)劣,只是向大家介紹一款開源的讀寫word文檔的組件。讀寫Excel有NPOI,讀寫Word,那看看DocX吧。下面跟著小編一起來(lái)學(xué)習(xí)學(xué)習(xí)吧。
    2016-12-12
  • 為ABP框架增加日志組件與依賴注入服務(wù)

    為ABP框架增加日志組件與依賴注入服務(wù)

    這篇文章介紹了為ABP框架增加日志組件與依賴注入服務(wù)的方法,文中通過(guò)示例代碼介紹的非常詳細(xì)。對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2022-02-02
  • asp.net網(wǎng)絡(luò)數(shù)據(jù)庫(kù)開發(fā)實(shí)例精解 源文件

    asp.net網(wǎng)絡(luò)數(shù)據(jù)庫(kù)開發(fā)實(shí)例精解 源文件

    asp.net網(wǎng)絡(luò)數(shù)據(jù)庫(kù)開發(fā)實(shí)例精解 源文件...
    2006-09-09
  • ASP.Net頁(yè)面生命周期與Page_Load方法的工作原理介紹

    ASP.Net頁(yè)面生命周期與Page_Load方法的工作原理介紹

    這篇文章介紹了ASP.Net頁(yè)面生命周期與Page_Load方法的工作原理,文中通過(guò)示例代碼介紹的非常詳細(xì)。對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2022-05-05

最新評(píng)論

石台县| 海林市| 义马市| 泰和县| 和林格尔县| 青阳县| 安龙县| 新疆| 荃湾区| 儋州市| 丽江市| 永吉县| 永嘉县| 高安市| 乐至县| 临武县| 衡阳市| 丹巴县| 盐亭县| 会泽县| 双牌县| 尼木县| 子洲县| 凤冈县| 天门市| 深泽县| 平陆县| 沈阳市| 庆城县| 永仁县| 兰考县| 墨竹工卡县| 明光市| 潮安县| 陵水| 五莲县| 南溪县| 孟州市| 扶风县| 云南省| 大埔区|