.net-4.8actionfilterattributehttp-status-code-406onactionexecutingonactionexecuted

.NET Framework 4.8 - return content on OnActionExecuting(HttpActionContext actionContext) error 406


I did store the resp on OnActionExecuted(HttpActionExecutedContext actionExecutedContext) in CacheManagerService, but when I want to use it in OnActionExecuting(HttpActionContext actionContext), it will return a http 406 or http 500 with no description.

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);
        }
    }
}

Note: it does work with Task<someClass> resp, but the problem is showing when I am using it on Task<IHttpActionResult> ODataController

Does anyone know how to fix this?


Solution

  • With the help of my friend, we found a solution for this.

    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);
            }
        }
    }