简体   繁体   English

转换 ASP.NET Core ActionResult<T> 对象到过滤器中的另一种类型

[英]Convert ASP.NET Core ActionResult<T> object to another type in a filter

I have a generic Result<T> type that I'm using from my business-level services to return results.我有一个通用的Result<T>类型,我在我的业务级服务中使用它来返回结果。 This type includes a property with the actual value ( public T Value {get;} ) as well as a status property that indicates Success, NotFound, ValidationError, or other options.此类型包括具有实际值的属性 ( public T Value {get;} ) 以及指示 Success、NotFound、ValidationError 或其他选项的状态属性。

In an API controller, I can evaluate the result of a service call and return an appropriate ActionResult like NotFound or Ok or BadRequest .在 API 控制器中,我可以评估服务调用的结果并返回适当的 ActionResult ,例如NotFoundOkBadRequest

I can manually do what I want in the method我可以在方法中手动做我想做的事

public ActionResult<Result<Customer>> GetCustomer(int id)
{
    Result<Customer> result = _someService.GetGetCustomer(id);
    if (result.Status == ResultStatus.NotFound) return NotFound();
    if (result.Status == ResultStatus.Invalid)
    {
        foreach (var error in result.ValidationErrors)
        {
            ModelState.AddModelError(error.Key, error.Value);
        }
        return BadRequest(ModelState);
    }

    return Ok(result.Value);
}

Example based on source here 示例基于此处的来源

but I'd like to be able to do this from within an ActionFilter instead.但我希望能够在 ActionFilter 中执行此操作。

The problem is I'm not having much success figuring out how to cast the value since I want the filter to work for any kind of T .问题是我在弄清楚如何转换值方面没有取得太大成功,因为我希望过滤器适用于任何类型的T Some pseudo code may help:一些伪代码可能有帮助:

[TranslateResultToHttp]
public ActionResult<Result<Customer>> GetCustomer(int id)
{
  Result<Customer> result = _someService.GetCustomer(int id);

  return Ok(result);
}

In my TranslateResultToHttpAttribute I'd need to take the resulting result, look at its value, and if it really was Ok I would replace Result<Customer> with just the Customer .在我的TranslateResultToHttpAttribute我需要获取结果结果,查看它的值,如果真的没问题,我会将Result<Customer>替换为Customer But if it were a NotFound I would return NotFound, etc.但如果它是 NotFound,我会返回 NotFound 等。

The problem is the filter has no idea what T the Result<T> might be, so I'm having a hard time unpacking the result to get its value, etc.问题是过滤器不知道Result<T>可能是什么 T,所以我很难解压结果以获取其值等。

Assuming your Result<T> type has a non-generic base interface that contains the pure status, you could just return the result directly, getting an implicit object result.假设您的Result<T>类型具有包含纯状态的非通用基接口,您可以直接返回结果,获得隐式对象结果。 And then you can implement a result filter to update the status code:然后你可以实现一个结果过滤器来更新状态代码:

public interface IResult
{
    int Result { get; set; } // could of course be something else
}

public class UpdateResultFilter : IResultFilter
{
    public void OnResultExecuting(ResultExecutingContext context)
    { }

    public void OnResultExecuted(ResultExecutedContext context)
    {
        if (context.Result is ObjectResult objectResult && objectResult.Value is IResult result)
        {
            // update status on object result
            objectResult.StatusCode = result.Status;
        }
    }
}

In the end, this is the same as returning specific results like NotFoundResult or BadRequestResult because these are just StatusCodeResult s with a predefinied status code.最后,这与返回NotFoundResultBadRequestResult等特定结果相同,因为这些只是带有预定义状态代码的StatusCodeResult

从 ActionResult 中获取值<object>在 ASP.Net Core API 方法中<div id="text_translate"><p>我尝试从 ASP.NET 核心 API 方法中的ActionResult&lt;object&gt;获取值。</p><p> API 有不同的 controller。 我尝试使用 controller A 中的 controller B 中的方法返回结果值。 我从 controller B 得到一个ActionResult object。我可以在ResultObject中使用调试器查看该值,但是如何访问其中的结果值?</p><pre> public ActionResult&lt;object&gt; getSourceRowCounter(string sourcePath) //Method from Controller A { var result = ControllerB.GetValue($"{sourcePath}.{rowCounterVariableName}"); var result2 = result.Value; //null var result3 = result.Result; //typ: {Microsoft.AspNetCore.Mvc.OkObjectResult} &lt;-see Value=4 in it with Debugger //var result4 = result3.Value; //Error?. //var result5 = result3;Content? //Error.? //var result6 = result3????;?; //How can i get the Value = 4? return Ok(result); //should only return value 4 and not the whole object }</pre> <p><img src="https://i.stack.imgur.com/4Lppi.jpg" alt="在此处输入图像描述"></p></div></object> - Get a Value from ActionResult<object> in a ASP.Net Core API Method

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 ASP.NET Core如何将任何类型转换为ActionResult <T> 控制器动作的返回类型? - How is ASP.NET Core able to convert any type to ActionResult<T> return type of controller actions? ASP.NET Core 6“无法将类型'Rotativa.ViewAsPdf'隐式转换为'Microsoft.AspNetCore.Mvc.ActionResult'” - ASP.NET Core 6 "Cannot implicitly convert type 'Rotativa.ViewAsPdf' to 'Microsoft.AspNetCore.Mvc.ActionResult'" ASP.NET Core API如何在操作方法中将ActionResult <T>转换为T. - How ASP.NET Core APIs convert ActionResult<T> to T in action methods ASP.net 核心 API 返回 ActionResult<t> 不强制返回类型</t> - ASP.net Core API returning ActionResult<T> not enforcing return type ASP.NET Core API - ActionResult<T> vs 异步任务<T> - ASP.NET Core API - ActionResult<T> vs async Task<T> 从 ActionResult 中获取值<object>在 ASP.Net Core API 方法中<div id="text_translate"><p>我尝试从 ASP.NET 核心 API 方法中的ActionResult&lt;object&gt;获取值。</p><p> API 有不同的 controller。 我尝试使用 controller A 中的 controller B 中的方法返回结果值。 我从 controller B 得到一个ActionResult object。我可以在ResultObject中使用调试器查看该值,但是如何访问其中的结果值?</p><pre> public ActionResult&lt;object&gt; getSourceRowCounter(string sourcePath) //Method from Controller A { var result = ControllerB.GetValue($"{sourcePath}.{rowCounterVariableName}"); var result2 = result.Value; //null var result3 = result.Result; //typ: {Microsoft.AspNetCore.Mvc.OkObjectResult} &lt;-see Value=4 in it with Debugger //var result4 = result3.Value; //Error?. //var result5 = result3;Content? //Error.? //var result6 = result3????;?; //How can i get the Value = 4? return Ok(result); //should only return value 4 and not the whole object }</pre> <p><img src="https://i.stack.imgur.com/4Lppi.jpg" alt="在此处输入图像描述"></p></div></object> - Get a Value from ActionResult<object> in a ASP.Net Core API Method 为什么 ASP.NET Core 操作可以返回 `ActionResult <IEnumerable<ZapResult> &gt;` 返回任何对象的 `BadRequest()`? - Why can an ASP.NET Core action returning an ` ActionResult<IEnumerable<ZapResult>>` return a `BadRequest()` of any object? 如何在asp.net core中编写自定义actionResult - How to write custom actionResult in asp.net core 如何在 ASP.NET 核心中使用 mysql 进行单元测试和操作结果 - How to unit test, actionresult with using mysql in ASP.NET Core ASP.NET Core中如何获取ActionResult StatusCode - How to get ActionResult StatusCode in ASP.NET Core
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM