简体   繁体   中英

HttpContext in .net standard library

I am working on couple of projects one of which is an ASP.NET 4.5 application and other one is .Net Core API 1.1 project. The asp.net application is using HttpContext classes to read cookies and page headers. Now, I need to move this to a .net standard library which can be used by both the project. I don't find HttpContext in .net standard SDK. Any suggestions?

There's a problem to your approach: .NET Standard is the most bare-bones implementation of .NET available, meaning that only basic features which are platform- and scenario-agnostic are implemented.
HttpContext exists on both the .NET Framework and .NET Core (both of which implement .NET Standard, by the way), but being specific to the Web, it does not exist on .NET Standard.

So, you have three options:

  1. Target the .NET Framework and use System.Web.HttpContext
  2. Target .NET Core and use Microsoft.AspNetCore.Http.HttpContext
  3. Move the logic that uses HttpContext away from the .NET Standard project

Do notice, though, that those classes vary greatly. The .NET Core version was created for ASP.NET Core which is vastly different to ASP.NET 4.5 and olders.

I do not agree with these answers and the non-sense about only having HttpContext in the web project. That is actually tightly coupled as YOU want to be able to re-use code and thus a class library in .net core OR .net standard SHOULD be able to use the HttpContext

So in a .NET Standard you want to add in :

Microsoft.AspNetCore.Http.Abstractions

Sadly though there is so much different about the new HttpContext HttpContext.Current is missing and thus session and request etc..

(Yes, I get the design patterns and why to separate out and make it more testable)

Here is a little trick you can pull off as well to get Current

namespace System.Web
{
    public static class HttpContext
        {
            private static Microsoft.AspNetCore.Http.IHttpContextAccessor m_httpContextAccessor;


    public static void Configure(Microsoft.AspNetCore.Http.IHttpContextAccessor httpContextAccessor)
        {
            m_httpContextAccessor = httpContextAccessor;
        }


        public static Microsoft.AspNetCore.Http.HttpContext Current
        {
            get
            {
                return m_httpContextAccessor.HttpContext;
            }
        }

    }
}

If you're targetting .NETStandard 2.0 you can work with HttpContext .

Though it is not included in the .NET Standard library, the Microsoft.AspNetCore.Http.Abstractions package (which targets .NET Standard 2.0) will enable you to work with HttpContext .

I need to move this [read cookies and page headers] to a .NET standard library which can be used by both the project...

Do NOT do this.

Let's assume you're performing an operation X on the data you read from the cookies. You may move this operation X to the library instead. The job of the ASP.NET projects is to handle the request pipeline. Reading the cookies belongs there.

I agree with the answer above you want to keep netstandard libraries simple and free of web requests if possible. There is a System.Net.Http nuget package that targets .net standard. This could be used when updating 4.6.x up for full framework and for .net core if you are creating a library and do not want the overhead of asp.net core.

One approach is to have the calling process pass the Http.Current.Request into a method in your Standard class as a parameter of type object. Then use Reflection to access the properties. In your Standard class, something like:

public void ProcessRequest(object Request)
{
    Type oT = Request.GetType();
    string URL = oT.GetProperty("RawUrl").GetValue(Request).ToString();
    // do something
}

Then from your calling application:

oRR.ProcessRequest(HttpContext.Current.Request);

I've tested this from .Net Framework, not from .Net Core. If the context library in Core has different properties, you might need to examine the type returned by GetType to decide which property names to access.

I know you want HttpContext but maybe will little help to create any channel. Therefore I give an ContextChannel example. Because I'm interested http context similar to that.

I just create ContextChannel and then I use OperationContext because If I've not created context scope Context Channel always is getting null.

In my example, it works following way;

  ChannelFactory<T> factory = channelFactory;
        factory.Endpoint.EndpointBehaviors.Add(new ClientMessagePropertyBehavior());

        var proxy = (IClientChannel)factory.CreateChannel();

  using (var contextScope = new OperationContextScope((IContextChannel)proxy))
            {
                Stopwatch sw = Stopwatch.StartNew();

                HttpRequestMessageProperty requestMessage = new HttpRequestMessageProperty();
                requestMessage.Headers["Authorization"] = accessToken;
                OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = requestMessage;

                TResult result = codeBlock((T)proxy);

                sw.Stop();

                _tools.logInfo(string.Format(@"* Service client performance : {0} = {1} ms", codeBlock.Method.ToString(), sw.ElapsedMilliseconds));

                success = true;
                return result;
            }

You can create HttpContext.Current before calling your old classes:

using System.Web; using System.Web.SessionState;

System.Web.HttpContext.Current = new System.Web.HttpContext(new System.Web.HttpRequest("", "http://localhost", ""), new System.Web.HttpResponse(new System.IO.StringWriter())); System.Web.SessionState.SessionStateUtility.AddHttpSessionStateToContext( System.Web.HttpContext.Current, new HttpSessionStateContainer("", new SessionStateItemCollection(), new HttpStaticObjectsCollection(), 20000, true, HttpCookieMode.UseCookies, SessionStateMode.InProc, false));

        HttpContext.Session.SetString("your_session_var", "1");

        foreach (string item in HttpContext.Session.Keys)
        {

            System.Web.HttpContext.Current.Session[item] = HttpContext.Session.GetString(item);

        }

**call your old class library methods

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM