在GitHub上有个项目,本来是作为自己研究学习.net core的Demo,没想到很多同学在看,还给了很多星,所以觉得应该升成3.0,整理一下,写成博分享给学习.net core的同学们。
项目名称:Asp.NetCoreExperiment
项目地址:https://github.com/axzxs2001/Asp.NetCoreExperiment
asp.net core mvc的模板中返回前端时可以用IActionResult的子类,来区分不同的返回内容,那怎么来实现自定义的ActionResult呢?
github代码如下:
https://github.com/axzxs2001/Asp.NetCoreExperiment/tree/master/Asp.NetCoreExperiment/Common/YamlResultDemo
首先引用一个三方包
PM> Install-Package YamlDotNet
YamlResult.cs
1 /// <summary> 2 /// YamlResul 3 /// </summary> 4 public class YamlResult : ActionResult 5 { 6 /// <summary> 7 /// Yaml值 8 /// </summary> 9 public object Value { get; private set; } 10 /// <summary> 11 /// 构造 12 /// </summary> 13 /// <param></param> 14 public YamlResult(object value) 15 { 16 Value = value; 17 } 18 /// <summary> 19 /// Result执行者 20 /// </summary> 21 /// <param>上下文</param> 22 /// <returns></returns> 23 public override async Task ExecuteResultAsync(ActionContext context) 24 { 25 var services = context.HttpContext.RequestServices; 26 var executor = services.GetRequiredService<IActionResultExecutor<YamlResult>>(); 27 await executor.ExecuteAsync(context, new YamlResult(this)); 28 } 29 }