How to access current absolute Uri from any ASP .Net Core class?

后端 未结 2 1520
忘掉有多难
忘掉有多难 2021-02-12 22:26

I am trying to figure out how to access the current absolute Uri -- i.e. the absolute url of the view that is currently being rendered -- from a user class in .

2条回答
  •  名媛妹妹
    2021-02-12 23:05

    You want the IHttpContextAccessor "configured or injected" in your Startup so later on when you use the helper during the context of a request you can use it to access the current HttpContext object.

    You cannot store the context on a static field as that context only makes sense while serving a specific request. Typically you will leave the accessor in a static field and use it every time your helper is called.

    • Even worse you are using static fields with initializers, which are executed the first time the class is used. That means they are executed right before you call the Configure method, so there will be no IHttpContextAccessor yet configured and you will get those null references.

    This would be a simple thing of writing what you want:

    public static class Context
    {
        private static IHttpContextAccessor HttpContextAccessor;
        public static void Configure(IHttpContextAccessor httpContextAccessor)
        {
            HttpContextAccessor = httpContextAccessor;
        }
    
        private static Uri GetAbsoluteUri()
        {
            var request = HttpContextAccessor.HttpContext.Request;
            UriBuilder uriBuilder = new UriBuilder();
            uriBuilder.Scheme = request.Scheme;
            uriBuilder.Host = request.Host.Host;
            uriBuilder.Path = request.Path.ToString();
            uriBuilder.Query = request.QueryString.ToString();
            return uriBuilder.Uri;
        }
    
        // Similar methods for Url/AbsolutePath which internally call GetAbsoluteUri
        public static string GetAbsoluteUrl() { }
        public static string GetAbsolutePath() { }
    }
    

    One more thing to bear in mind:

    • In the original question, the helper was created as a static class because they were created as extension methods. If you are not using extension methods you are not forced to use a static class.

提交回复
热议问题