.NET Framework 4.8 - 返回 OnActionExecuting(HttpActionContext actionContext) 错误 406 的内容

问题描述 投票:0回答:1

我确实将resp存储在

OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
中的
CacheManagerService
上,但是当我想在
OnActionExecuting(HttpActionContext actionContext)
中使用它时,它将返回http 406或http 500,没有描述。

using System.Net.Http;
using System.Net;
using Newtonsoft.Json;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
using System.Web.Http;

namespace ***.Mvc.ActionFilters
{
    public class SampleAttribute : ActionFilterAttribute
    {
        public override async void OnActionExecuting(HttpActionContext actionContext)
        {
            base.OnActionExecuting(actionContext);

            var respCache = GetCache(key);

            if (respCache != null)
            {
                actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.OK, await resp.ReadAsAsync(typeof(object)));
            }
        }

        public override async void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
        {
            base.OnActionExecuted(actionExecutedContext);
            SetCache(key,actionExecutedContext.Response.Content);
        }
    }
}

注意:它确实可以与

Task<someClass>
配合使用,但当我在
Task<IHttpActionResult> ODataController

上使用它时,问题就出现了

有人知道如何解决这个问题吗?

.net-4.8 actionfilterattribute http-status-code-406 onactionexecuting onactionexecuted
1个回答
0
投票

在我朋友的帮助下,我们找到了解决方案。

using System.Net.Http;
using System.Net;
using Newtonsoft.Json;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
using System.Web.Http;

namespace ***.Mvc.ActionFilters
{
    public class SampleAttribute : ActionFilterAttribute
    {
        public override async void OnActionExecuting(HttpActionContext actionContext)
        {
            base.OnActionExecuting(actionContext);

            var respCache = GetCache(key);

            if (respCache != null)
            {
                **var resp = (HttpContent)respCache;
                var value = await resp.ReadAsAsync(typeof(object));
                HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
                response.Content = new ObjectContent(value.GetType(), value, GlobalConfiguration.Configuration.Formatters.JsonFormatter);
                actionContext.Response = response;**
            }
        }

        public override async void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
        {
            base.OnActionExecuted(actionExecutedContext);
            SetCache(key,actionExecutedContext.Response.Content);
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.