Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8198741
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 7, 20262026-06-07T06:00:55+00:00 2026-06-07T06:00:55+00:00

I am trying to create a [LoggedApiCall] filter for a Get() on an ApiController

  • 0

I am trying to create a [LoggedApiCall] filter for a Get() on an ApiController
According to this: ASP.NET Web API ActionFilter example

I have created a System.Web.HttpFilters.ActionFilterAttribute.
The override allows for OnActionExecuted(HttpActionExecutedContext actionExecutedContext)

I cannot seem to find a way to get the IP of the caller from the HttpActionExecutedContext

Perhaps I am going about logging every API call the wrong way?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-07T06:00:57+00:00Added an answer on June 7, 2026 at 6:00 am

    We use the following filter which we add to HttpConfiguration.Filters. Some code:

    internal class LoggingFilter : IExceptionFilter, IActionFilter
    {
        private readonly ILog log;
    
        public LoggingFilter(ILog log)
        {
            if (log == null)
            {
                throw new ArgumentNullException("log");
            }
    
            this.log = log;
        }
    
        public bool AllowMultiple
        {
            get { return false; }
        }
    
        Task IExceptionFilter.ExecuteExceptionFilterAsync(HttpActionExecutedContext actionContext, CancellationToken cancellationToken)
        {
            if (actionContext == null)
            {
                throw new ArgumentNullException("actionContext");
            }
    
            this.log.Error(string.Format("Unexpected error while executing {0}", this.BuildLogEntry(actionContext.ActionContext)), actionContext.Exception);
            return TaskHelpers.Completed();
        }
    
        Task<HttpResponseMessage> IActionFilter.ExecuteActionFilterAsync(HttpActionContext actionContext, CancellationToken cancellationToken, Func<Task<HttpResponseMessage>> continuation)
        {
            if (actionContext == null)
            {
                throw new ArgumentNullException("actionContext");
            }
    
            if (continuation == null)
            {
                throw new ArgumentNullException("continuation");
            }
    
            if (!this.log.IsDebugEnabled)
            {
                // no point running at all if logging isn't currently enabled
                return continuation();
            }
    
            string logEntry = this.BuildLogEntry(actionContext);
            IDisposable logContext = this.log.DebugTiming("Executing {0}", logEntry);
    
            Task<string> requestContent;
            if (actionContext.Request.Content != null)
            {
                requestContent = actionContext.Request.Content.ReadAsStringAsync().ContinueWith(requestResult => string.IsNullOrEmpty(requestResult.Result) ? "N/A" : requestResult.Result);
            }
            else
            {
                requestContent = TaskHelpers.FromResult("N/A");
            }
    
            return requestContent.ContinueWith(
                requestResult =>
                    {
                        this.log.DebugFormat("{0}, Request = {1}", logEntry, requestResult.Result);
    
                        return continuation()
                            .ContinueWith(t =>
                                {
                                    Task<string> responseContent;
                                    if (t.IsCompleted && t.Result.Content != null)
                                    {
                                        responseContent = t.Result.Content.ReadAsStringAsync().ContinueWith(responseResult => string.IsNullOrEmpty(responseResult.Result) ? "N/A" : responseResult.Result);
                                    }
                                    else
                                    {
                                        responseContent = TaskHelpers.FromResult("N/A");
                                    }
    
                                    return responseContent.ContinueWith(
                                        responseResult =>
                                            {
                                                using (logContext)
                                                {
                                                    this.log.DebugFormat("{0}, Status Code: {1}, Response = {2}", logEntry, t.Result.StatusCode, responseResult.Result);
                                                }
    
                                                return t.Result;
                                            });
                                }).Unwrap();
                    }).Unwrap();
        }
    
        /// <summary>
        /// Builds log data about the request.
        /// </summary>
        /// <param name="actionContext">Data associated with the call</param>
        private string BuildLogEntry(HttpActionContext actionContext)
        {
            string route = actionContext.Request.GetRouteData().Route.RouteTemplate;
            string method = actionContext.Request.Method.Method;
            string url = actionContext.Request.RequestUri.AbsoluteUri;
            string controllerName = actionContext.ActionDescriptor.ControllerDescriptor.ControllerName;
            string actionName = actionContext.ActionDescriptor.ActionName;
    
            return string.Format("{0} {1}, route: {2}, controller:{3}, action:{4}", method, url, route, controllerName, actionName);
        }
    }
    

    We use log4net, you can replace the ILog implementation with whatever you see fit. ILog.DebugTiming is just an extension method that uses a Stopwatch to get elapsed time for each call.

    Edit:
    This post Get the IP address of the remote host has details on how to get the IP address of the remote caller.

    Cheers,
    Dean

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

hi I'm trying create chat using node.js I see example in http://chat.nodejs.org/ I have
I've been trying create this simple ish to-do list web app using JavaScript &
Trying to create a new Dedicated Cache Role in Windows Azure but get the
Trying to create a background-image slideshow and am getting this error... This is the
I'm trying create a RCP Application with Eclipse, but I can't get past the
I'm trying create a ASMX webservice that can perform a HTTP GET request. I
I trying create a class derivated from System.Web.UI.Page and in override Render i set
I am trying create a small web application that allows a user to login
Trying to create the following routine in MySQL Workbench yields a This object's DDL
I'm trying create this function such that if any key besides any of the

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.