Getting controller return status code for web api

403 Views Asked by At

I am writing a record with the OnActionExecuting method, how can I get the status code of the request

LogActionAttribute : ActionFilterAttribute

    public override void OnActionExecuting(HttpActionContext filterContext)
        {

            _stopwatch.Stop();

            var controller = filterContext.RequestContext.RouteData.Values["Controller"];
            var action = filterContext.RequestContext.RouteData.Values["Action"];
            var url = filterContext.Request.RequestUri;
            var Method = filterContext.Request.Method;
            StreamReader reader = new StreamReader(HttpContext.Current.Request.InputStream);
            var statusCode = //get status code 
            var req_txt = reader.ReadToEnd();
            var requestResponseModel = new RequestResponseModel()
            {
                /* Url = request.Url.LocalPath.ToString(),
                 Method = request.HttpMethod,
                 Ip = request.UserHostAddress,
                 RequestDate = DateTime.Now,
                 Expires = response.Expires,
                 RequestParams = req_txt,
                 ContentType = request.ContentType*/

            };

            string json = JsonConvert.SerializeObject(new { id = '2', sifre = 'c' });

            //write string to file
            System.IO.File.AppendAllText(HttpContext.Current.Server.MapPath("~/Tmp/jsondata.txt"), json);


            base.OnActionExecuting(filterContext);
        }
1

There are 1 best solutions below

3
On BEST ANSWER

The OnActionExecuting is executed before the action is run. The status code does only provide meaningful information after the action is run. Even if there is a response object available that you could get the status code from, the real status code is only available
Therefore, you could use the OnActionExecuted method to access the status code that was set by the action.

For details, see this link. Though this link describes the behavior of filters for MVC, the basic mechanism is the same for the filters in Web API.