【问题标题】:Wrapping results of ASP.NET Core WebAPI methods using IResultFilter使用 IResultFilter 包装 ASP.NET Core WebAPI 方法的结果
【发布时间】:2018-04-14 21:23:02
【问题描述】:

我已经实现了一个这样的结果过滤器:

public class ResultWrapperFilter : IResultFilter
{
    public void OnResultExecuting(ResultExecutingContext context)
    {
        if (!(context.ActionDescriptor is ControllerActionDescriptor))
        {
            return;
        }

        var objectResult = context.Result as ObjectResult;
        if (objectResult == null)
        {
            return;
        }

        if (!(objectResult.Value is WrappedResponseBase))
        {
            objectResult.Value = new WrappedResponse(objectResult.Value);
        }
    }

    public void OnResultExecuted(ResultExecutedContext context)
    {
    }
}

通过ConfigureServices(IServiceCollection services) 配置MvcOptions 来使用过滤器,如下所示:

public void ConfigureServices(IServiceCollection services)
{
    services.Configure<MvcOptions>(
            options => { options.Filters.AddService<ResultWrapperFilter>(); });
    services.AddMvc();

    // ... the rest is omitted for readability
}

我遇到的问题是这个过滤器导致InvalidCastException: Unable to cast object of type 'WrappedResponse' to type 'System.String'(有问题的方法有字符串作为返回值类型)。

我什至可以使用 IResultFilter 执行此操作吗?

注意:我知道使用中间件来完成响应包装的可能性。我不想使用中间件来完成此操作,因为中间件无权访问context.Result as ObjectResult。从响应流中反序列化,再次包装和序列化似乎没有必要。

【问题讨论】:

    标签: asp.net-core asp.net-core-mvc asp.net-core-webapi asp.net-core-2.0


    【解决方案1】:

    我刚刚得到了答案。 设置objectResult.Value时,objectResult.DeclaredType也需要设置。

    所以在这种情况下:

    if (!(objectResult.Value is WrappedResponseBase))
    {
        objectResult.Value = new WrappedResponse(objectResult.Value);
        objectResult.DeclaredType = typeof(WrappedResponse);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-10
      • 2019-09-22
      • 1970-01-01
      • 2017-04-04
      • 2017-10-30
      • 1970-01-01
      • 2020-07-11
      • 2019-07-28
      相关资源
      最近更新 更多