如何在asp.net core中编写自定义actionResult

编程入门 行业动态 更新时间:2024-10-10 04:24:43
本文介绍了如何在asp core中编写自定义actionResult的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

在 webApi2 中,我可以通过继承 IHttpActionResult 编写自定义 ActionResult.

In webApi2 i could write a custom ActionResult by inheriting IHttpActionResult.

示例:

public class MenivaActionResult : IHttpActionResult { private readonly HttpRequestMessage _request; private readonly ServiceResponseBase _response; public MenivaActionResult(HttpRequestMessage request, ServiceResponseBase response) { _request = request; _response = response; } public Task<HttpResponseMessage> ExecuteAsync(CancellationToken token) { HttpResponseMessage httpresponseMessage = _response.Exception != null ? _request.CreateErrorResponse((HttpStatusCode)_response.HttpCode, _response.Exception.Message+":"+_response.Exception.HelpCode) : _request.CreateResponse((HttpStatusCode)_response.HttpCode, _response.Data); return Task.FromResult(httpresponseMessage); } }

ServiceResponseBase 类对象包含来自服务层的所有异常和数据..

The ServiceResponseBase class object holds all the exception and data from service layer..

我如何将此代码移植到 asp 核心.我试过了,但我不知道如何从 核心中的 HttpRequestMessage 对象创建响应消息.IActionResult 只有 Task ExecuteResultAsync(ActionContext context) 方法.我如何修改此方法的响应

How i can port this code to asp core. I tried but i dont know how create a response message from HttpRequestMessage object in core. The IActionResult only have Task ExecuteResultAsync(ActionContext context) method. how i can modify the response from this method

推荐答案

这是一个例子:

public class TestResult { public Exception Exception { get; set; } public object Data { get; set; } } public class TestActionResult : IActionResult { private readonly TestResult _result; public TestActionResult(TestResult result) { _result = result; } public async Task ExecuteResultAsync(ActionContext context) { var objectResult = new ObjectResult(_result.Exception ?? _result.Data) { StatusCode = _result.Exception != null ? StatusCodes.Status500InternalServerError : StatusCodes.Status200OK }; await objectResult.ExecuteResultAsync(context); } }

ObjectResult 是如果您从操作返回非IActionResult 的结果将被转换的类型.它将为您进行内容协商.

ObjectResult is the type your results are converted if you return a non-IActionResult from an action. It will do content negotiation for you.

您也可以从 ObjectResult 继承并设置要写入构造函数的状态代码和数据.

You could also inherit from ObjectResult and setup the status code and data to be written in the constructor.

有关 ASP.NET Core 内容协商的更多信息:docs.microsoft/en-us/aspnet/core/mvc/models/formatting#content-negotiation

More on content negotiation in ASP.NET Core: docs.microsoft/en-us/aspnet/core/mvc/models/formatting#content-negotiation

更多推荐

如何在asp.net core中编写自定义actionResult

本文发布于:2023-11-14 03:54:56,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1586142.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:自定义   如何在   asp   net   core

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!