HttpResult from service crash in NET8/SS8

Hi again,
There’s been some changes to SS8/NET8, because my code that was running isn’t anymore. Well most of it is.

This part crashes:

I’m getting this message:

No service for type ‘Microsoft.AspNetCore.Http.IHttpContextAccessor’ has been registered.

What I’m doing at the line that crashes is:

        return new HttpResult(cell, HttpStatusCode.Created)
        {
            Location = new CellDetail { Id = savedCell._id }.ToAbsoluteUri(),
            Headers = {
               { "X-Location", new CellDetail { Id = savedCell._id }.ToAbsoluteUri() },
            }
        };

I guess a workaround is to change the Api, and just return a DTO, but I want to let you know that this has been working fine until today.

My project was converted from a SS6/NET7 project. All I did was to change the version numbers in the project files, as my project was already built with these kind of Configure.xxx files:

[assembly: HostingStartup(typeof(Mindcell.ConfigureAuth))]

Is there a “upgrade guide” or something that I should’ve followed?

The full stack-trace below:

[CellCreateOrUpdate: 26.01.2024 20:11:56]:
[REQUEST: {title:test cell2,description:"",work:3,stealFromParentsWork:True,progress:0,completed:False,discardRemaining:False,parentId:610181793761}]

System.InvalidOperationException: No service for type 'Microsoft.AspNetCore.Http.IHttpContextAccessor' has been registered.
    at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)
    at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService[T](IServiceProvider provider)
    at ServiceStack.AppHostBase.TryGetCurrentRequest() in /home/runner/work/ServiceStack/ServiceStack/ServiceStack/src/ServiceStack/AppHostBase.NetCore.cs:line 532
    at ServiceStack.HostContext.TryGetCurrentRequest() in /home/runner/work/ServiceStack/ServiceStack/ServiceStack/src/ServiceStack/HostContext.cs:line 330
    at ServiceStack.HttpExtensions.ToAbsoluteUri(String relativeUrl, IRequest req) in /home/runner/work/ServiceStack/ServiceStack/ServiceStack/src/ServiceStack/HttpExtensions.cs:line 44
    at ServiceStack.HttpExtensions.ToAbsoluteUri(IReturn requestDto, String httpMethod, String formatFallbackToPredefinedRoute) in /home/runner/work/ServiceStack/ServiceStack/ServiceStack/src/ServiceStack/HttpExtensions.cs:line 16
    at Mindcell.ServiceInterface.CellServices.Post(CellCreateOrUpdate req) in C:\Programming\MindCell\mindcell23\Mindcell\api\Mindcell.ServiceInterface\CellServices.cs:line 77
    at ServiceStack.Host.ServiceRunner`1.ExecuteAsync(IRequest req, Object instance, TRequest requestDto) in /home/runner/work/ServiceStack/ServiceStack/ServiceStack/src/ServiceStack/Host/ServiceRunner.cs:line 149

Can you share the stacktrace?

One thing you could try is registering the required dependency (that’s what the error message is complaining about), eg:

builder.Services.AddHttpContextAccessor();

Or

builder.Services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
1 Like

Did you change anything related to your IoC/DI container setup or is your application using a custom/different AppHost that isn’t inheriting from AppHostBase? The default AppHostBase will configure this missing dependency automatically, which makes me think you might be inheriting from a different base class for your AppHost or overriding something that is missing this step.

Are there any other errors in the output before this error?

That won’t solve it, I’ve cleaned up the formatting of your stacktrace, this issue is coming from the extension method ToAbsoluteUri.

1 Like

To avoid registering a HttpContextAccessor you can provide the IRequest in the ext method:

new CellDetail { Id = savedCell._id }.ToAbsoluteUri(base.Request)
1 Like

This made the error go away. I only used the ToAbsoluteUri extension method three places, from within a service, so it was a quick fix, and is running fine.

I do of course wonder why it happened, but with such quick replies from you two guys, the problem is never big. If anyone else is reading this, I got replies during the weekend, from multiple core developers. And this is only one of three posts, same response time on all.

1 Like

So passing the Request to the extension method has solved my immediate problem. I don’t have the error anymore.

Of course, it’s strange that it happened in the first place, working in SS6/NET7, so I’ve provided some more info:

To help you debug further, should you want to:

  • My Program.cs is identical to the newest templates. I’m comparing to the newest v8 VueVite template.

  • My AppHost class is also the same, i.e. public class AppHost : AppHostBase, IHostingStartup.

Looking futher at my Configure.AppHost.cs for differences with the standard template:

All I have different is that I’ve added:

.ConfigureAppConfiguration((context, configBuilder) => {
    configBuilder.AddJsonFile("secrets.json");
})

in the public void Configure(IWebHostBuilder builder), and this part in the end:

        JsConfig.Init(new Config
        {
            DateHandler = DateHandler.ISO8601,
            AlwaysUseUtc = false,
            ExcludeDefaultValues = false,        
            IncludeNullValues = false
        });

        LogManager.LogFactory = new SerilogFactory(new Serilog.LoggerConfiguration()
            .MinimumLevel.Information()
            .WriteTo.File(Path.Combine(AppSettings.Get("LogPath", "."), "mindcell.log"),
                rollingInterval: RollingInterval.Day)
            .CreateLogger());

        // enable when new SS version supports Async auth repo
        //Plugins.Add(new AdminUsersFeature());

The service where it crashed was just a plain service, like this:

public class CellServices : Service

(I’ve confirmed that Service referes to ServiceStack.Service.)

My SS version is 8.0.1, using MyGet. Yesterday, or the day before, I cleared my Nuget cache before restoring packages. I’ve even added clearing the cache as a step in my Dockerfile, however the problem is outside of docker as well (using Docker just for deployment, same problem both places).

Dotnet version 8.0.100.

I’m sure there’s somewhere I’ve done something, and perhaps there are changes in NET8 that have affected this. Just want to give the info, since you guys replied in the weekend and all.

1 Like

If you don’t provide the IRequest context and if you don’t have Config.WebHostUrl configured, then ServiceStack needs to resolve the Request Context via singleton in order for ToAbsoluteUri() to determine the absolute URL which is constructed with the incoming Request URL.

This was always possible in .NET Framework with HttpContext.Current but the only way this is possible in .NET Core is by registering the IHttpContextAccessor which is no longer registered by default as of .NET Core 2+. If you didn’t have it registered explicitly than another component/feature that you were using could’ve registered it, e.g. VS automatically registers Application Insights by default when debugging.

ServiceStack doesn’t register the IHttpContextAccessor, so something else you used must have.