Recent Comments



Lee
Friday

re: Back to Basics: Custom HTTP Response Header Manipulation in ASP.NET Core

This is excellent. I've been having the same problem in trying to manipulate the response headers. I used this technique of the custom middleware shown here. It adds headers no problem but it wasn't removing them. I did post the issue on github but maybe here is better 😃


Jake Coyne
August 09, 2022

re: Windows Authentication with HttpClient

@Rick - thank you it was entirely my mistake in assuming that it was looking for NTLM (based on the domain credentials). Your answer led me down the right path, thank you so much!


Rick Strahl
August 09, 2022

re: Windows Authentication with HttpClient

@Jake - you probably have to check a request that works and compare that indeed the server works with Windows authentication. You should hook up an HTTP proxy (like Fiddler) and see what gets sent - you should see the Negotiate header being sent to the server. Whether the server uses that correctly is another story, but that's what checking with some other mechanism verifies whether the UID and Password are valid and Windows Auth is actually what hte server is looking for. The server should be responding with a 401 along with the supported protocols in the headers.


Rick Strahl
August 09, 2022

re: JavaScript Debugging in a Web Browser Control with Visual Studio

@Johnx - yup, but that dialog is very noisy and whether the debugger pops up depends on configuration and security settings - it's very unreliable and annoying if you forget to turn it off. Best not to muck with that one I think.


Jake Coyne
August 09, 2022

re: Windows Authentication with HttpClient

Rick, Thank you for this, your writings are very helpful. I am wondering if you can offer some advice on why it might still be failing. If I access my API endpoint via a web browser it will ask for my credentials and if I provide my network credentials return the expected JSON. However, when I try this code:

Uri uri = new Uri("MY URL");
CredentialCache credentialsCache = new CredentialCache { { uri, "Negotiate", new NetworkCredential("USER", "PASS", "DOMAIN") } }; //Have also tried ("DOMAIN\\USER", "PASS") format
HttpClientHandler handler = new HttpClientHandler { Credentials = credentialsCache, PreAuthenticate = true };
HttpClient httpClient = new HttpClient(handler) { BaseAddress = uri, Timeout = new TimeSpan(0, 0, 10) };
httpClient.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
var response = await httpClient.GetAsync(uri);
string json = await response.Content.ReadAsStringAsync();

I get a 401 Unauthorized every time. I have tried using NTLM instead of Negotiate, with and without PreAuthenticate and always the 401 response. Unfortunately, the service I am calling is a third party I don't have much control over and I am currently out of ideas.


Johnx
August 08, 2022

re: JavaScript Debugging in a Web Browser Control with Visual Studio

There is another IE flag in the options above that also help, it covered by bottom of red box and defaulted off. You can 'enable' the option to be 'notified of every script error' ( lots of popups). Tells you file/line#/errormsg. By default you can't jump into the debugger, unless attached, but this will popop with hints and correct line #'s. So helpful.


Henke
August 04, 2022

re: Using WSL to Launch Several Bash Commands from an Application

32 bit applications do not look in System32
– Do you mean 64 bit applications do not look in System32?


Marc W
August 02, 2022

re: Combining Bearer Token and Cookie Authentication in ASP.NET

@Steve Hunt, you saved my day. I have mixed mode in core 6. after jwt my Identity mvc login stopped to work. This line resumed to work with jwt for api an cookie for asp/mvc

return IdentityConstants.ApplicationScheme;

Bryant
July 29, 2022

re: VSIX Installer Extension Manifest and Visual Studio Version Numbers

Hi Rick,

I agree about the PITA nature of VSIX. I'm running into a targetversion issue that led me here. I'm curious if you have experience with it.

I am updating an existing item templates VSIX project. The item templates make use of the WizardExtention. Those templates can only refer to a single version of VS. I need to have a set of item templates for VS2019 and a set for VS2022 because of the required difference in the WizardExtension values. I have attempted to get that to happen using the TargetVersion setting on the Assets tab in the Extension Manifest editor. What I am expecting is that if I set an asset to v17 or above, v16 won't be able to see it. And that isn't happening whether I use the UI or the XML document.

In the VSIX manifest schema description it says "TargetVersion - the version range to which the given asset applies. Used for shipping multiple versions of assets to different versions of Visual Studio." so I think I'm in the right place.

Are you familiar with the settings or do you have any other ideas?

Thanks


Firegarden
July 25, 2022

re: IDbCommand and generic Parameters

Hi Rick, Have you considered the option of just making your own objects out of the interfaces?

Thank you, Rob

public class DbDataParameter : DataParameter, IDbDataParameter
{
    public byte Precision { get; set; }
    public byte Scale { get; set; }
    public int Size { get; set; }
}

Rick Strahl
July 24, 2022

re: .NET Core 3.0 SDK Projects: Controlling Output Folders and Content

@Cathei - yeah, it'd be nice if <projectReference> worked but unfortunately it doesn't. Setting <private>false</private> has no effect and still pulls in all dependencies of the referenced project, unlike the DLL reference.


Noe
July 22, 2022

re: Prettifying a JSON String in .NET

This is exactly what I was looking for to simply print Azure SDK responses. Thanks!


Slobodan Gajinovic
July 22, 2022

re: SmtpClient and Locked File Attachments

Hello folks!

I have found the same problem, but using wwSMTP class… How could I release locks from attachment files, after the message had been sent, but from VFP application? Workarounds presented here are not applicable to VFP code.

I couldn’t find at wwSMTP code any reference to message object (neither to attachments objects), where could I make an explicit dispose() call. Calling loSmtp.dispose() doesn’t release lock from recently added attachments. The locks remain active untill application quit (or I didn’t find workaround solution).

Simple code example:

DO wwSmtp && load libraries
LOCAL loSMTP as wwSmtp
loSmtp = CREATEOBJECT("wwSmtp")
loSmtp.nMailMode = 0  
loSmtp.cMailServer = "smtp.office365.com:587"  
loSmtp.cSenderEmail = "Test_sender@MyCompany.com"
loSmtp.cSenderName = "Test sender"
loSmtp.cUsername = "Test_sender@MyCompany.com"
loSmtp.cPassword = "********"
loSmtp.lUseSsl = .T.
loSmtp.cSubject = "Test1"
loSmtp.cContentType = "text/html"
loSmtp.cMessage = "Test1"
lcAttachmentFile = "Test1.PDF"
loSmtp.AddAttachment(lcAttachmentFile)
loSmtp.ntIMEOUT = 30
loSmtp.Connect()
loSmtp.SendMessage("Test_Receiver@gmail.com")
loSmtp.Close()
losmtp.dispose  && this doesn't release lock from file Test1.PDF
losmtp = null
RELEASE loSmtp

*!* At this moment, file which had been attached to email message ("Test1.PDF") 
*!* remains locked (untill application quit) and it cannot be deleted or moved out.

* (...)
 
QUIT 


Rick Strahl
July 19, 2022

re: Fighting WebView2 Visibility on Initialization

@John - yeah this kind of hackery often works for things in WPF in general. I have similar things that i do during startup basically moving the window offscreen, making it visible, letting all the base config happen then snap it into the actual window position when it's ready, which is much crisper than the wiggly natural initialization.

This trick of temporarily making the WebView visible though appears to be too fast to actually have a visual impact. I think the DispatcherPriority.Render is enough to trigger whatever UI events the control needs to get past the visibility block.

Unfortunately I played around with this in the many tabs scenario of Markdown Monster and there I couldn't get this to work because these phantom activations are essentially async and I can't control the order so they end up stepping on each other and end up activating the wrong tabs. But the trick definitely is a good one if you have a single control that is hidden and needs to immediately initialize.

It might also help with pre-loading content so it doesn't slow load into the browser.


John Schroedl
July 19, 2022

re: Fighting WebView2 Visibility on Initialization

Interesting finding. Thanks for posting this we have plans to use the virtualhostname feature soon and this could head off some trouble.

This reminds me of an ugly hack I needed to perform where you could visibly see the WPF data binding of a list occurring. When the window was made visible, you'd see the old content which re-bound and then showed the new content. My only workaround (with help from Rob Relyea) was to make the list initially "invisible" with Opacity = 0 and then set to 1 to truly show it. That allowed the initial binding to happen out of sight.


Kalai
July 19, 2022

re: Handling SPA Fallback Paths in a Generic ASP.NET Core Server

I want to call the angular component from the MVC controller. when I am calling the MVC controller from there to redirect angular registration page any idea


Rick Strahl
July 18, 2022

re: Fighting WebView2 Visibility on Initialization

@Dalibor - No I don't regret using the WebView despite all the issues I've run into and have worked around 😄. The truth is that other controls have other issues. I've used CEF Sharp before and had a completely different set of issues with that. As I did with the old WebBrowser control.

At the end of the day, integrating a browser that is essentially an external OS/native component is tricky and you'll end up with issues around the integration.


Edwin
July 18, 2022

re: WebView and Modal Dialogs in WPF Async Code

I'm experiencing a similar issue with WebView2 (1.0.1245.22), but only when the debugger is attached. After enabling 'native code debugging' the debugger breaks when this issue occurs, as shows the following message:

Running a message loop synchronously in an event handler in Webview can cause reentrancy issue. Please refer to https://docs.microsoft.com/en-us/microsoft-edge/webview2/concepts/threading-model#re-entrancy for more information about threading model in WebView2 and how to enable native code debugging for this scenario.
A breakpoint instruction (__debugbreak() statement or a similar call) was executed in MyApp.exe.

So this seems to be a check/warning that is deliberately added. I guess your issue is the same.


David
July 16, 2022

re: Fighting WebView2 Visibility on Initialization

I really love the fact that you document your investigation (including dead ends that you went down!) because that helps me realize that I’m not the only one who gets stuck trying to work around crazy limitations like this. Please keep up the great work on your blog - it helps us all learn not only what the end result is, but also all the troubleshooting techniques along the way.


Michael Gallo
July 16, 2022

re: Runtime C# Code Compilation Revisited for Roslyn

What a fantastic article! I came across it while converting our C# scripting from Mono to Roslyn, and it was a big help.

I do have one issue though, and I was wondering whether you've perhaps encountered it as well: Despite adding a reference to the executing assembly, I get a System.IO.FileNotFoundException in System.RuntimeMethodHandle.InvokeMethod saying that the executing assembly could not be found (even though the path is correct).

I suspect it's because we have a native host, loading a managed dll from an external path, which is then doing the compilation etc., but I'm not sure. If I don't add the reference, everything works, but obviously the Roslyn-compiled code can't call methods in the executing assembly.


Dalibor Čarapić
July 16, 2022

re: Fighting WebView2 Visibility on Initialization

Do you regret using webview2 and not using CEF or something else?


Rick Strahl
July 14, 2022

re: .NET Core 3.0 SDK Projects: Controlling Output Folders and Content

@Miguel - Visual Studio uses a custom version of MSBuild that behaves differently than the version that's used in dotnet build from the command line. Other than what's in this post I don't know of another solution...


Miguel
July 14, 2022

re: .NET Core 3.0 SDK Projects: Controlling Output Folders and Content

Hi Rick,

I run into this problem some time ago an this post helped me sort out the output of a project using a similar plugin architecture when we moved to .net core.

This is all working fine when we build from Visual Studio which uses MSBuild.

We are now moving to containers and using multi stage builds in docker where we use dotnet build MySolution.sln to do the actual building.

For some reason dotnet build even on windows produces a different output to what MSBuild used to so we are again getting some extra files in the output folder. This also happens if you we use Rider as it uses dotnet build under the hood.

Do you have any pointers as to how to fix this again on dotnet build?

Thanks!


DaveG
July 14, 2022

re: Fixing Visual Studio Intellisense Errors

Just updated VS2022 and had this problem. Code compiled fine but lots of intellisense issues. Deleting the .vs folder cleared it up. Saved me a few hours poking around to figure it out myself....


Jim
June 30, 2022

re: Runtime C# Code Compilation Revisited for Roslyn

Wow Rick, you are an animal with the content! Well done.


Howard
June 28, 2022

re: Back to Basics: Rendering Razor Views to String in ASP.NET Core

MVC views are a somewhat complicated way to render HTML strings. I used to use RazorEngine for this in old ASP.NET.

When we upgraded to Blazor/.NET 6 I looked for a Razor Component-based system and couldn't find one, so wrote my own: https://github.com/conficient/BlazorTemplater


Thomas Ardal
June 25, 2022

re: Back to Basics: Rendering Razor Views to String in ASP.NET Core

@Rick Ahh, you're right. I copied your method signature to make the code similar to your example. Don't think I can change the comment, though.


Rick Strahl
June 24, 2022

re: Back to Basics: Rendering Razor Views to String in ASP.NET Core

@Thomas - your static method won't be able to see the RazorViewEngine so you'd have to pass it into that method.

@Soundar - yeah lots of people commenting in regards to standalone solutions which is great, but that's not what this post is about. It's specifically meant for the scenario where you can use what's already provided in the application without additional dependencies.


Soundar
June 24, 2022

re: Back to Basics: Rendering Razor Views to String in ASP.NET Core

This looks great. But, for people looking for out of the box solution, they can try https://github.com/soundaranbu/RazorTemplating.

The major advantage is that it works outside of the MVC context. This means, they can use it in console applications as well.


Thomas Ardal
June 24, 2022

re: Back to Basics: Rendering Razor Views to String in ASP.NET Core

This is pretty much what I'm doing to render an invoice from a Razor view and then convert the HTML to a PDF file. I found that it's easier to just inject the IRazorViewEngine where I need it like this:

public MyController(IRazorViewEngine razorViewEngine)
{
    this.razorViewEngine = razorViewEngine;
}

public static async Task<string> RenderViewToStringAsync(
    string viewName, object model,
    ControllerContext controllerContext,
    bool isPartial = false)
{
    var actionContext = controllerContext as ActionContext;
    
    using (var sw = new StringWriter())
    {
        var viewResult = razorViewEngine.FindView(actionContext, viewName, !isPartial);
        ...
    }
}

Rick Strahl
June 23, 2022

re: Windows Authentication with HttpClient

@Waleed - For HttpClient you can use UseDefaultCredentials on the HttpClientHandler (or SocketHandler). Another way is to use CredentialCache.DefaultNetworkCredentials - haven't tried the latter however.


Waleed
June 23, 2022

re: Windows Authentication with HttpClient

Thanks for excellent post, this is exactly what I was looking for. The only issue that does not work for me is the credentials, is there a way to use current user windows credentials, the web service I am calling is running on IIS accepting windows authentication for internal web service


Rick Strahl
June 22, 2022

re: Back to Basics: Rendering Razor Views to String in ASP.NET Core

@Tobias - I haven't tried this, but you still end up with dependency on the ServiceProvider that's been populated by the ASP.NET startup in order to work. I think without those dependencies many things likely won't work - especially the path and view folder resolutions.


Tobias Bartsch
June 22, 2022

re: Back to Basics: Rendering Razor Views to String in ASP.NET Core

I used a similar approach to render my email templates but without an active http request. I just create my own ActionContext like this. I don't know if it works in all circumstances, but it was perfectly adequate for my needs.

    private ActionContext GetActionContext()
    {
        var httpContext = new DefaultHttpContext();
        httpContext.RequestServices = _serviceProvider;

        var currentUri = new Uri("htpps://myDomain.tdl"); // Here you have to set your url if you want to use links in your email
        httpContext.Request.Scheme = currentUri.Scheme;
        httpContext.Request.Host = HostString.FromUriComponent(currentUri);
        
        return new ActionContext(httpContext, new RouteData(), new ActionDescriptor());
    }

Rick Strahl
June 21, 2022

re: Back to Basics: Rendering Razor Views to String in ASP.NET Core

@Joe - I hear you and I agree. It's possible to do outside of ASP.NET in say a desktop app, but you then still end up pulling in the ASP.NET libraries to make it happen. And getting a ControllerContext that works as expected is a pain. There are a couple of projects out there that do this, but they don't look very solid.

I had a library for full framework, but there too it was a royal pain in the ass to get it to work and there are lots of limitations running outside of ASP.NET there too. I would love to do this for Core again, but I can't justify the work for that. I've resigned myself to use custom C# scripting using Handlebars like syntax in a small library instead:

and there are other libraries like Fluid (Liquid template language) that also uses a handlebars like syntax, but without the C# language structures.


Rick Strahl
June 21, 2022

re: .NET WebRequest.PreAuthenticate – not quite what it sounds like

@Kumar - no, this is a client specific thing. The server will do what it must to authenticate - Challenge on no auth header, and accept the header if provided.

The client is who has to decide how to initially send the data to the server.


Joe Enos
June 21, 2022

re: Back to Basics: Rendering Razor Views to String in ASP.NET Core

I just wish it was easier to do it outside the context of a web request. There are times when I want to build HTML somewhere else, and have to use Mustache or Handlebars.

I've seen some people try to implement it, but there always seem to be disclaimers that it may or may not always work for whatever reasons.

It would have been awesome if Microsoft would have made Razor a standalone templating engine, and then plugged it into ASP.NET.


Kumar
June 21, 2022

re: .NET WebRequest.PreAuthenticate – not quite what it sounds like

Is there a way to enable preemptive authentication at the server, OS, or app.config level? We have a .NET 2.0 C# application running on Server 2016 POSTing to a Linux box running the recipient's web service. But opening up our code to add the header is not an option. We see a 100->401->100->200 sequence for every transmission. I proposed leaving it the way it is for the marginal security benefit. But we need to be prepared if our customer wants to reduce server load & network traffic in the future. Thank you so much for allowing me to address this issue in an informed way with our customer's IT staff!


Dan
June 12, 2022

re: Runtime C# Code Compilation Revisited for Roslyn

@Dan - In full framework (not in .NET Core) you can use AppDomains to isolate code although that has certain limitations in how data can be passed around. Generally though that is no longer supported in .NET Core.

Docker? Really? If you need to isolate on that level, why not just create an executable and run that in a totally separate process which gives you full isolation from the host process (but not the host OS of course in which case Docker may make sense).


Dan S
June 11, 2022

re: Runtime C# Code Compilation Revisited for Roslyn

Hi Rick,

I studied this topic before. I want run user-submitted code in a ASP.NET Core backend.

Is there any way to isolate the code when it is running? Or limit it's resources? Like the CPU time or memory?

I think the best solution would be spinning up a new Docker container and compiling and running the code there. Then I could isolate and limit the whole container and not just the user-submitted code.6g

Thanks, Dan


Rick Strahl
June 09, 2022

re: Runtime C# Code Compilation Revisited for Roslyn

Jos - that's not something for Roslyn - you need the debugger APIs for that.


Jos Wilson
June 09, 2022

re: Runtime C# Code Compilation Revisited for Roslyn

Hi Rick, You keep on impressing me with your vast knowledge on .Net, Wonderful article and really helped me a lot to get started. An important question for me is, how can I get Roslyn to step through my code like the debugger does and does it keep track of the 'Instruction Pointer'. So in concept can I get roslyn to step through my code like the good old CodeDom did?


RandomDude
June 02, 2022

re: Role based JWT Tokens in ASP.NET Core APIs

Thanks a lot for sharing Rick. I just spent some not-so-fun-time trying to figure why I kept getting 401 errors when trying to access endpoints with Authorize-tag. I was way too focused on a possible jwt-related issue. Turned out that my local iis-express was configured with { "windowsAuthentication": true, "anonymousAuthentication": false }. It dawned upon my when I saw that my Bearer-auth was not even considered during the request. Instead the server always expected auth via NTLM. Now everything is all fun and colorful rainbows again ^^


Daniel Souchon
May 20, 2022

re: More on ASP.NET Core Running under IIS

I am hosting an asp.net core website on IIS having following recommended steps It starts up fine and displays a list of inventory in an html table (jquery datatables) being pulled from SQL server database and using Entity Framework. All good BUT if I then refresh the same page once or twice or click the button to fetch the data again "Service unavailable. 503.0. Server was shut down" I have produced all the logs and none of them give an error besides a request and 503 response. If I test using the kestrel URL I cannot reproduce the bug - so I don't think it's a code error. Any ideas? Am I configuring something wrong? Where to look for answers? Website in question is : https://stokseek.colms.net/ Thanks for any help!


NLNet
May 13, 2022

re: WebView2 Flashing when changing TabControl Tabs

Hi Rick, Thank you for your excellent post and I have some diffirent idea about the flash of WebView2 here. It is base your achievement 😃.

I will be glad to discuss with you.


Rick Strahl
May 11, 2022

re: Debouncing and Throttling Dispatcher Events

If it's on this blog it's free to use.

I'm not going to put a bloody license on every bit of code I post.


Andrei
May 11, 2022

re: Debouncing and Throttling Dispatcher Events

Hi Rick, What is the license for the above DebounceDispatcher code? Thanks in advance!


vandana
May 09, 2022

re: Adding minimal OWIN Identity Authentication to an Existing ASP.NET MVC Application

Thanks Rick, finally an article which cleared the clutter and highlighted the essential pieces.

My setup: My app is a .net 4.6 framework app and is not using system.web.mvc, instead it is a layered app. It is called by a frontend in angular, which calls api routes which in turn land on the .net app controllers which are based on system.web.http and uses token based authentication. Currently, we use AuthenticationFilterAttribute for implementing authentication.

We now need to integrate this app with external login providers like google, fb etc.

My question is as follows:

  1. Do i need to add system.web.mvc to use owin startup class, ChallengeResult (inhereting from HttpUnauthorizedResult which is only in system.web.mvc and and all related code)?

  2. Can I continue to use token based authentication, or will Cookie based authentication need to be used in order to have the external 3rd parties integrated?

  3. Will I need to remove the AuthenticationFilterAttribute and just have the owin startup be r responsible for authentication?

Thanks for your help.


Sam
May 06, 2022

re: Missing Sharing Tab in Windows Explorer and Sharing with PowerShell

Thanks so much, the cmdlet worked for me, everything else was correctly set, but yet the Sharing was missing in mine.