Fork me on GitHub

asp.net core mvc中自定义ActionResult

在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 name="value"></param>
14         public YamlResult(object value)
15         {
16             Value = value;
17         }
18         /// <summary>
19         /// Result执行者
20         /// </summary>
21         /// <param name="context">上下文</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     }

YamlResultExecutor.cs

 1     /// <summary>
 2     /// YamlResult执行者
 3     /// </summary>
 4     /// <typeparam name="T"></typeparam>
 5     public class YamlResultExecutor<T> : IActionResultExecutor<T> where T : YamlResult
 6     {
 7         /// <summary>
 8         /// 执行
 9         /// </summary>
10         /// <param name="context">上下文</param>
11         /// <param name="result"></param>
12         /// <returns></returns>
13         public async Task ExecuteAsync(ActionContext context, T result)
14         {
15             var serialize = new YamlDotNet.Serialization.Serializer();
16             var valueString = serialize.Serialize(result.Value);
17             // 把对象转成yaml字符串,用Response返回
18             context.HttpContext.Response.ContentType = "Content-Type: text/html; charset=utf-8";
19             await context.HttpContext.Response.WriteAsync(valueString);
20         }
21     }

 

TestController.cs中调用代码

        [HttpGet]
        public IActionResult Get()
        {
            return new YamlResult(new
            {
                Data = new { a = 1, B = "bbb", C = DateTime.Now, d = new string[] { "a", "b", "c" } },
                Status = true,
                Message = "成功"
            });
        }

运行结果:

posted @ 2019-10-25 09:15  桂素伟  阅读(2522)  评论(0编辑  收藏  举报