简体   繁体   中英

HttpContext works differently in visual studio Code with OmniSharp extension

I installed Visual Studio Code and install C# Extension

https://marketplace.visualstudio.com/items?itemName=ms-vscode.csharp

When I open existing Asp.Net Core 2 project I can edit files and run web server with debug option ( Debug > Start Debugging )

But then I got null exception about HttpContext (debug from visual studio 2017 do not throw this error)

@User.Identity.Name.Replace(@"Domain\", string.Empty)

When I change code to

@System.Security.Principal.WindowsIdentity.GetCurrent().Name.ToString();

It works. So it seems to me that C# Extension run different web server or with different settings than Visual Studio 2017. I have assumption that issue can be in Windows Authentication setting , but i dont have clue where to setup this ?

Any idea ?

This is related with hosting Asp.Net Core . In general, there are three options for launching new project, IIS , IIS Express and Project . When launching from VS 2017 , you may use IIS Express which supports Windows Authentcation and you could configure it by launchsettings.json .

But, launching from IIS or IIS Express is not supported in VS Code . Then you will lauch .NET Core by Project when using VS Code . When you use self-hosted by Project , you will need to use Http.sys with Windows Authencation to support Windows Authentication .

For resolving your issue, you could modify Program.cs like below to use Http.sys with Windows Authentcation .

public static IWebHost BuildWebHost(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseStartup<Startup>()
                .UseHttpSys(options => {
                    options.Authentication.Schemes =
                        AuthenticationSchemes.NTLM | AuthenticationSchemes.Negotiate;
                        options.Authentication.AllowAnonymous = false;
                })
                .Build();

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