Click here to Skip to main content
15,886,873 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
We are now dealing with converting our .NET Framework C# code to .NET Core and having some difficulty in the following:
A very generic method we have in a class library (DLL) is this:

C#
public static (string, string) InitMethod(bool SetWocContentType = true, [CallerMemberName] string callerName = "", bool printLog = true, bool setThreadName = false)
        {
            const string WocContentType = "application/json; charset=utf-8";

            string caller = Generic.GetSessionParam(SessionParams.Caller);
            string callerText = $"{caller} {callerName}".Trim();

            if (setThreadName)
            {
                string userId = System.Web.HttpContext.Current?.Request?.Params["UserId"] ?? Generic.GetSessionParam(SessionParams.TenantUID); 
                if (string.IsNullOrEmpty(System.Threading.Thread.CurrentThread.Name))
                {
                    System.Threading.Thread.CurrentThread.Name = !string.IsNullOrEmpty(userId ) ? $"{userId } ({callerName})" : $"({callerName})";
                }
            }

            if (printLog) NLogger.Instance.Debug($"{callerText} Starting");

            if (SetWocContentType && System.ServiceModel.Web.WebOperationContext.Current != null && System.ServiceModel.Web.WebOperationContext.Current.OutgoingResponse != null && System.ServiceModel.Web.WebOperationContext.Current.OutgoingResponse.ContentType != null)
            {                System.ServiceModel.Web.WebOperationContext.Current.OutgoingResponse.ContentType = WocContentType;
            }

            return (caller, callerText);
        }
        public static string GetSessionParam(SessionParams param)
        {
            string myName = "GetSessionParam"; //Cannot call InitMethod as it call GetSessionParam within and will result in StackOverflow..
            NLogger.Instance.Trace($"{myName} Asking for value ({param})");
            
            string value = "";
            if (HttpContext.Current != null && HttpContext.Current.Items.Contains(param.ToString()))
            {
                value = HttpContext.Current.Items[param.ToString()] as string;
            }
            if (!param.Equals(SessionParams.Config))
            {
                NLogger.Instance.Trace($"{myName} Returning with ({value})");                
            }
            else
            {
                NLogger.Instance.Trace($"{myName} Returning with ({value.CutByPrefixSuffix(3, 3)})");                
            }
            return value;
        }


I need to convert this code to .NET Core 6.0 but encounter a problem when working with HttpContext and WebOperationContext.
Can anyone please help me with this?

What I have tried:

I managed to convert the code to this but passing HttpContext as parameter - I don't think it's possible from lots of places in the code:
C#
public static (string?, string?) InitMethod(HttpContext httpContext, bool SetWocContentType = true, [CallerMemberName] string callerName = "", bool printLog = true, bool setThreadName = false)
        { 
            const string WocContentType = "application/json; charset=utf-8";

            string? caller = GetSessionParam(httpContext, SessionParams.Caller);
            string callerText = $"{caller} {callerName}".Trim();

            if (setThreadName)
            {
                string? userId = null;
                if (!string.IsNullOrEmpty(httpContext.Request.Query["UserID"]))
                {
                    userId = httpContext.Request.Query["UserID"];
                }
                else
                {
                    userId = Generic.GetSessionParam(httpContext, SessionParams.UserUID);
                }
                
                if (string.IsNullOrEmpty(Thread.CurrentThread.Name))
                {
                    Thread.CurrentThread.Name = !string.IsNullOrEmpty(userId ) ? $"{userId } ({callerName})" : $"({callerName})";
                }
            }

            if (printLog) NLogger.Instance.Debug($"{callerText} Starting");

            if (SetWocContentType && OperationContext.Current != null && httpContext.Response != null && httpContext.Response.ContentType != null)
            {
                httpContext.Response.ContentType = WocContentType;
            }

            return (caller, callerText);
        }

        private static string? GetSessionParam(HttpContext context, SessionParams param)
        {
            string myName = "GetSessionParam"; //Cannot call InitMethod as 
            // it calls GetSessionParam within and will result 
            // in StackOverflow..
            NLogger.Instance.Trace($"{myName} Asking for value ({param})");

            // Get the session object from the context.
            var session = context.Session;

            byte[] value;
            // Check if the session param exists.
            if (!session.TryGetValue(param.GetDescription(), out value))
            {
                // The session param does not exist.
                return null;
            }
            string? result = Encoding.UTF8.GetString(value);
            if (!param.Equals(SessionParams.Config))
            {
                NLogger.Instance.Trace
                    ($"{myName} Returning with ({result})");
            }
            else
            {
                NLogger.Instance.Trace($"{myName} 
                Returning with ({result.CutByPrefixSuffix(3, 3)})");
            }
            return result;
        }
Posted
Updated 10-Aug-23 10:18am
v2
Comments
Graeme_Grant 6-Aug-23 20:32pm    
with Asp.Net Core, alot of this is now done in middleware. ref: ASP.NET Core Middleware | Microsoft Learn[^]
oronsultan 7-Aug-23 2:43am    
Can you please elaborate?
We have web services exposing nothing but API's. The web service is reference with a set of DLLs (class library) that are generic.
Is it possible to access request url params or current session params from a class library?

1 solution

If your service really needs access to the full HttpContext, then you can inject the IHttpContextAccessor[^] service and use that to access the current context. However, you cannot inject services into a static method; you would need to inject the service into the caller, and pass the context as a parameter.

It would be better to create specific service interface(s) for your class library's exact requirements, and inject/pass an implementation that delegates to the current context. That way, you make your code more testable. Eg:

Class library:
C#
public interface ISessionParamProvider
{
    string? GetSessionParam(string name);
}

private static string? GetSessionParam(ISessionParamProvider provider, SessionParams param)
{
    string myName = "GetSessionParam"; //Cannot call InitMethod as it call GetSessionParam within and will result in StackOverflow..
    NLogger.Instance.Trace($"{myName} Asking for value ({param})");
    
    string? result = provider.GetSessionParam(param.GetDescription());
    if (result is null)
    {
        // The session param does not exist.
        return null;
    }
    
    if (!param.Equals(SessionParams.Config))
    {
        NLogger.Instance.Trace($"{myName} Returning with ({result})");
    }
    else
    {
        NLogger.Instance.Trace($"{myName} Returning with ({result.CutByPrefixSuffix(3, 3)})");
    }
    
    return result;
}
Web application:
C#
public class SessionParamProvider : ISessionParamProvider
{
    private readonly IHttpContextAccessor _contextAccessor;
    
    public SessionParamProvider(IHttpContextAccessor contextAccessor)
    {
        ArgumentNullException.ThrowIfNull(contextAccessor);
        _contextAccessor = contextAccessor;
    }
    
    public string? GetSessionParam(string name)
    {
        var session = _contextAccessor.HttpContext?.Session;
        if (session is null)
        {
            // There is no current context, or session state is disabled:
            return null;
        }

        byte[] value;
        // Check if the session param exists.
        if (!session.TryGetValue(name, out value))
        {
            // The session param does not exist.
            return null;
        }
        
        return Encoding.UTF8.GetString(value);   
    }
}

var builder = WebApplication.CreateBuilder(args);
...
builder.Services.AddHttpContextAccessor();
builder.Services.AddTransient<ISessionParamProvider, SessionParamProvider>();
...

Access HttpContext in ASP.NET Core | Microsoft Learn[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900