Recent Comments



Jonathan Ramos
Thursday

re: Accepting Raw Request Body Content in ASP.NET Core API Controllers

Thanks for this! I was frustrated for not being able to receive the a JSON string to work without Binding. To be able to Deserialize to different classes I removed escape characters from the string.

rawBodyStream.Replace('\n', ' ').Replace('\r', ' ')


Rick Strahl
Wednesday

re: Running .NET Core Apps on a Framework other than Compiled Version?

@Max - no real problem, other than it takes up space, and it gets hard to look at when you do dotnet --info. Hard to see at a glance when you have 3 pages of runtimes installed.


Max
Wednesday

re: Running .NET Core Apps on a Framework other than Compiled Version?

Great post! A nasty topic really demystified ๐Ÿ™‚ Well done!

A question, if not sanitizing (deleting runtime folders), what kind of problems do you experience?


Spencer Swindell
Wednesday

re: Custom Message Formatting in WCF to add all Namespaces to the SOAP Envelope

Just wanted to say thanks for this post! I'm working with a SOAP API that presents the same challenges you faced here, and your post helped me get it working. Thanks for the walkthrough and explanation!


Rick Strahl
Wednesday

re: Running .NET Core Apps on a Framework other than Compiled Version?

@Przemyslaw - no it's not impossible, but the default configuration if you don't explicitly override the version, doesn't run a lower version. You can force it via the runtimeconfiguration.json file and as you point by using dotnet --fx-version.

I forgot about the latter, and have added it to the post. Thanks!


Przemyslaw
June 15, 2021

re: Running .NET Core Apps on a Framework other than Compiled Version?

I am wondering if it is really impossible to run assemblies compiled for lower version on higher version runtimes. Just a few days ago I managed to run xunit.console runner, which is netcoreapp2.0, on .NET 5 runtime using command dotnet --fx-version "5.0.6". I needed to run dotnet-trace over it and it worked perfectly fine.


Rick Strahl
June 15, 2021

re: Which .NET Core Runtime Download do you need?

@Kruti - Here's a post that has more detail about runtime 'roll-forward' functionality: Running .NET Core Apps on a Framework other than Compiled Version?


Rick Strahl
June 15, 2021

re: Which .NET Core Runtime Download do you need?

@Kruti - Unfortunately the answer is No. .NET Core apps have to have a same major version runtime installed in order to work. Unlike full framework which can run older version binaries, .NET Core requires at least the major version to be the same.

So running a .NET Core 2.x app on .NET Core 5.0 only does not work. Running a .NET 2.0 app on a system that has .NET Core 2.1 installed should work on the other hand. However the reverse is not true - running a 3.1 on a system that only has 3.0 will also not work.


Kruti Joshi
June 14, 2021

re: Which .NET Core Runtime Download do you need?

Thanks for this explaination!

I also want to clarify another thing - dotnet --info shows me that I have .Net Core SDK 5.0.301 active. To be clear, this should be okay to run apps with target framework .Net Core 2.1 since the SDK would be backward compatible, right?


Rick Strahl
June 14, 2021

re: Chromium WebView2 Control and .NET to JavaScript Interop - Part 2

There's is no WebBrowser.Document in WebView2. You can only interact with the browser via ExecuteScriptAsync(codeToEval).

Is it possible to interact with the DOM? Yup and I show examples in this post. Is it as easy as with the Web Browser control? Nope...

If you control the code on the client, it's better to write a front end in JavaScript and interact with that front end from .NET. That way you can do the complex code natively without dealing with string encoding issues. In part 3 I show some helpers that make Interop easier, but even with that it's still a bit of work to go back and forth.


justanotherguy
June 14, 2021

re: Chromium WebView2 Control and .NET to JavaScript Interop - Part 2

Is it possible to use an HTML editor with webview2 that accesses the dom like webbrowser.document?


Rick Strahl
June 12, 2021

re: PC and Mac with single Mouse and Keyboard Setup on Dual 4k Screens

@Scott - Using the Logitech software, it handles the switch between machines/monitors. But you need to have two (or three) monitors for this to work. There's nothing fancy here. Each machine has its own 'normal' setup for the monitor from machine to monitor. There's no KVM - just multiple monitors that are active/on all the time.


Scott
June 12, 2021

re: PC and Mac with single Mouse and Keyboard Setup on Dual 4k Screens

This is a great article. I am curious how do you get it to switch your monitors to the active machine? What wires are plugged in where and how? I am trying to do a similar setup with a Mac and PC and am banging my head against bad KVM experiences.

Thank you very much in advance!


Dez
June 12, 2021

re: Resetting Entity Framework Migrations to a clean Slate

What should I do if there are multiple contexts sharing the same database. In particular, may I use the usual routine commands when enabling, adding migration and updating databse?


Chess and Onions
June 07, 2021

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

Have you been messing with the Ultimate Windows Tweaker? That was my problem. The context menu lets you disable "Give Access To" option, which in fact is Sharing.


Ludovic
June 04, 2021

re: XSD.EXE and included schemas?

If you have a lot of xsd, you should use a configuration file. For example GenerateClassFromXSD.xml :

<xsd xmlns='http://microsoft.com/dotnet/tools/xsd/'>
<generateClasses language='CS' namespace='Namespace.subnamespace'>
    <schema>A2.xsd</schema>
    <schema>A21.xsd</schema>
    <schema>.\A22.xsd</schema>
</generateClasses>
</xsd>

It is very important to have the ".\" in last xsd declaration (otherwise, you will have a too big filename > 260 car.)

xsd /p:GenerateClassFromXSD.xml

See the final tips here : https://stackoverflow.com/questions/3859319/tool-that-can-combine-many-xsd-files-into-one/7000894


James
June 03, 2021

re: Async/Await Calls Gotcha with the CSharp ? Null Propagator

I haven't tested it, but I suspect the syntax for the suggested TaskExtensions will still require parenthesis, albeit in a slightly nicer place

await (EditorHandler?.JsEditorInterop?.SetFocus()).EnsureAwaitable();

This is because the elvis operator stops at the first null in a chain - if EditorHandler was null, then it wouldn't call EnsureAwaitable without the parenthesis.


Peter
May 27, 2021

re: Chromium WebView2 Control and .NET to JavaScript Interop - Part 2

What well written and informative articles. Not sure where you find time to write any code as it seems to me all your time would go into creating this great content. Looking forward to Part 3. Keep it up. Thanks, Peter


Rick Strahl
May 27, 2021

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

@OzBob - you can't refresh a token because the thing is basically a snapshot with the expiration part of the signature. Once it expires it's done.

I think the way to deal with this is to expect a client application to fail with an invalid token and have custom functionality around that. A couple of things I've done for this:

  • Add a custom RefreshToken endpoint - you have to be authenticated and it'll issue you a new token that resets the timeout.
  • When the token gets close to expiring add a new Token to the outgoing request say in an HTTP header that the client app can check for to pick up a new token for extension.

Neither of these is a built-in feature, so this relies on application specific logic.


OzBob
May 26, 2021

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

Once the token expires, how do you refresh it?


Thomas Levesque
May 26, 2021

re: WebView2 Home and End Key Problems inside of WPF TabControl Containers

No wonder you couldn't change this behavior with KeyboardNavigation properties, it's hard-coded.

I don't really understand the explanation in the comments, but there must be a good reason why they did this...


Pankaj
May 25, 2021

re: Chromium WebView2 Control and .NET to JavaScript Interop - Part 2

Hi, Any pointers to how to capture keypress or click events of ALL controls from a page loaded in webview2 control? My .Net application wants to know which button/control was clicked and possibly pass some additional data along with it to .Net host application.


Dima
May 24, 2021

re: Don't let ASP.NET Core Console Logging Slow your App down

Is this true for .NET 5.0?

If not, you can use this code, instead of the authors:

if (env.IsProduction())
{
    var consoleLogger = services.FirstOrDefault(x => x.ImplementationType == typeof(ConsoleLoggerProvider));
    services.Remove(consoleLogger);
}

Steve
May 18, 2021

Rick Strahl
May 17, 2021

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

The fact that you can decode the token doesn't mean that it's valid, because the portion that you are displaying is not encoded. The key for ASP.NET validation is the key hash that is encoded with the application level key that is used to validate the data and ensure its integrity with the server key and timeout.

To test - make sure it works without the roles first. Remove the role check and just check user access. If that works, then you can look into why it doesn't work with the role.


Josh
May 17, 2021

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

So I'm getting really close on this, but for some reason I still can't hit my endpoint if it has the [Authorize(Roles = MyRoles.Administrator)] attribute. I think that I have set it up properly... When I decode my token, I get the following payload:

{
  "sub": "administrator",
  "jti": "ba9f388a-591b-4be1-ae9a-a3aa52b90b84",
  "username": "administrator",
  "userid": "34613a8d-40eb-469e-a37a-98060ee4bf0d",
  "http://schemas.microsoft.com/ws/2008/06/identity/claims/role": "Administrator",
  "exp": 1621293379,
  "iss": "https://localhost:44308/",
  "aud": "https://localhost:8090/"
}

Any ideas why I would get the proper payload but still cannot hit my endpoint (I do hit the endpoint if I remove the attribute)? My biggest suspicion is my Issuer and Audience strings. I have tried simply https://mysite.com in case just anything would work, and I've tried https://localhost:44308/ for issuer and https://localhost:8090/ since these are the domains of my web API and my UI project.


Rick Strahl
May 17, 2021

re: Async/Await Calls Gotcha with the CSharp ? Null Propagator

Thanks @Thomas - fixed his comment.@Yury - I'd hope there's no change to the way this works compared to the sync call. If it's different then the whole language feature addition becomes pointless IMO.


Thomas Levesque
May 17, 2021

re: Async/Await Calls Gotcha with the CSharp ? Null Propagator

I was going to suggest the same solution as Mattias, but I think the usage example is wrong. It should be ...?.SetFocus().EnsureAwaitable(), not ...?.SetFocus()?.EnsureAwaitable(); otherwise EnsureAwaitable() won't be called on null.


Yury Schkatula
May 17, 2021

re: Async/Await Calls Gotcha with the CSharp ? Null Propagator

I would laugh if that syntax proposal will end up like that:

await? EditorHandler?.JsEditorInterop?.SetFocus()

Rick Strahl
May 17, 2021

re: Async/Await Calls Gotcha with the CSharp ? Null Propagator

@Danthar - no, SetFocus() cannot return null, because it's an async method. How could you possibly return null from it? The compiler won't allow it. If you remove the async you can potentially do it but not with the generated C# code that goes with async.


Danthar
May 17, 2021

re: Async/Await Calls Gotcha with the CSharp ? Null Propagator

if i understand this all correctly. Its failing because the SetFocus function returns null instead of a Task, in that case then....

Your first solution does not work. SetFocus can still return a null task. thus explode on the await.

Only your second solution is correct. Since then you handled this case and await is always executed on a valid Task instance.

In my humble opinion the fact that SetFocus can return null instead of a task is a bug in the API


Mattias
May 17, 2021

re: Async/Await Calls Gotcha with the CSharp ? Null Propagator

Maybe introduce a little extension method? ๐Ÿ˜€

    cpp
    
        
    
 public static class TaskExtensions

{ public static Task EnsureAwaitable(this Task? task) // The name is so-so... ๐Ÿคจ { return task ?? Task.CompletedTask; } }

Now you can simply call:

    css
    
        
    
 await EditorHandler?.JsEditorInterop?.SetFocus().EnsureAwaitable();

Rick Strahl
May 12, 2021

re: Taking the new Chromium WebView2 Control for a Spin in .NET - Part 1

@Paul - No I don't think there's anything on the control. If there is check on WebBrowser.CoreWebView2 . if there's nothing there, you could override window.onerror= function() { return false; } with ExecuteScriptAsync() to basically ignore errors.


Paul
May 12, 2021

re: Taking the new Chromium WebView2 Control for a Spin in .NET - Part 1

Hey on the standard web browser control there was an option in winforms:

webBrowser.ScriptErrorsSuppressed = true;

Is there something similar when using WebView2 at all? - Currently, I don't care about the errors that pop up! "Script Error": https://tinyurl.com/2j3t4ttk


Khang Azun
May 12, 2021

re: External Network Access to Kestrel and IIS Express in ASP.NET Core

Dear Rich,

I was frustrated with exposing .NETCore webapp to external in MacOS for almost a day.

You saved my day. Thanks a lot. -Khang


Rick Strahl
May 11, 2021

re: Chromium WebView2 Control and .NET to JavaScript Interop - Part 2

@Ravi - That's because you're not actually navigating the browser in a SPA app. You're only manipulating the history. Not sure if there is something on the control that can handle this, but you can always capture the routing event in the browser and forward it to the host. I think the window.onpushstate event might be what you want to look at and then use JavaScript interop to push the change notification into .NET.


Ravi Vanzara
May 10, 2021

re: Chromium WebView2 Control and .NET to JavaScript Interop - Part 2

I am using Webview2 to load my react.js web application that uses route to change the url but unfortunately it doesn't raise the NavigationStarting event.

Can you suggest some way to detect navigation Change.


Rick Strahl
May 03, 2021

re: Back to Basics: When does a .NET Assembly Dependency get loaded

@Garry - yes that's expected behavior. If a type is referenced in a function the type and its assembly have to be loaded. It doesn't need to execute. As you mention using a wrapper to decide which method to run or - in the case of Linux vs. Windows code - you can use a wrapper that checks the OS and then fires the appropriate method. Good idea with this platform specific code anyway.


Garry Thomas
May 03, 2021

re: Back to Basics: When does a .NET Assembly Dependency get loaded

Hi Rick, I have found that the loading of an Assembly may be triggered when a method containing a reference to a Type is called, even if the actual code is not executed.

I have .netstandard2.0 library that runs on both Windows and Linux with this code...

internal static bool VerifyServiceLogOn()
{
    if (Environment.OSVersion.Platform == PlatformID.Win32NT)
    {
        var runningAsLocalSystem = System.Security.Principal.WindowsIdentity.GetCurrent().User.IsWellKnown(System.Security.Principal.WellKnownSidType.LocalSystemSid);
        /*...code removed to simplify...*/
        return runningAsLocalSystem;
    }
}

It causes an Assembly load failure on Linux (due to an BadImageFormatException of System.Security.Principal.Windows.dll). I fixed it by putting the conditional OSVersion check in a separate method which then calls this method..

internal static bool VerifyServiceLogOn()
{
    if (Environment.OSVersion.Platform == PlatformID.Win32NT)
    {
        return verifyServiceLogOn();
    }
    return true;
}
private static bool verifyServiceLogOn()
{
    var runningAsLocalSystem = System.Security.Principal.WindowsIdentity.GetCurrent().User.IsWellKnown(System.Security.Principal.WellKnownSidType.LocalSystemSid);
    /*...code removed to simplify...*/
    return runningAsLocalSystem;
}

Is this expected behaviour? I expect its some sort of optimization by the compiler somehow?

Regards Garry


Graham Furner
April 26, 2021

re: Use Powershell to bind SSL Certificates to an IIS Host Header Site

Very helpful, thank you.

Although a couple of typos threw me for a while:

dir certs:\localmachine\my

should be:

dir cert:\localmachine\my


Tom
April 22, 2021

re: Blank Zero Values in .NET Number Format Strings

Excellent thank you!

This is perfect for displaying int values of zero as blank cells in my WPF grid.


Ali
April 22, 2021

re: WCF WS-Security and WSE Nonce Authentication

Anthony Miller, man you saved me. I was banging my head against wall on how to solve these issues and found nothing for password digest. I was having same error as gilson or token cannot be authorized. Just build the XML, replaced the values and it worked like a charm.


Rick Strahl
April 20, 2021

re: Role based JWT Tokens in ASP.NET Core

@Christof - you can't 'logout' with JWT Tokens. A token once generated is valid until it expires, so from the server side you can't invalidate a token, unless you add some secondary authentication layer around it: For example keeping track of tokens issues in a Db or even memory and looking up the token when it's validated to see if it's still valid.

If you use the token in a client application you can remove a login cookie, or the API token stored on the client and that effectively logs the client out, but in theory the token is still valid and if used will still work.


Rick Strahl
April 20, 2021

re: Taking the new Chromium WebView2 Control for a Spin in .NET - Part 1

@Wes - if that's what the site says then that's what it is. Nobody should be using anything older than .NET 4.62 anyway for building .NET Framework apps.


Wes Ong
April 20, 2021

re: Taking the new Chromium WebView2 Control for a Spin in .NET - Part 1

Hi Rick, just curious, you mentioned in your article that:

The WebView2 .NET integration that provides the WPF and WinForm controls, is shipped as a NuGet package that you can add to your WPF or WinForms project. The NuGet Package supports both WPF and WinForms versions of the control so regardless which you use and it works both in Full .NET Framework (NETFX) as well as .NET Core.

Did you test which minimum version of .NET Framework supports WebView2?

From the WebView2 site, it seems to suggest V4.6.2 or later.


Rob Kent
April 19, 2021

re: Taking the new Chromium WebView2 Control for a Spin in .NET - Part 1

Yes that is what you would expect. We deployed our app today with the new WebView2 and immediately got reports of SSRS reports being broken. Seems like it doesn't respect the client desktop's regional settings and the date 2021-04-16 was rendering as 21/04/16. There is a Github issue for it. Not sure what the workaround is yet since we don't have any regional code ourselves - we just accept parameters on the URL.


Christof Jans
April 18, 2021

re: Role based JWT Tokens in ASP.NET Core

Great post. I still have a question :

How do you invalidate a token ? How does a user log out ?


Rick Strahl
April 13, 2021

re: Debugging the Web Browser Control with FireBug

@manoj - Firebug is no longer around. Got discontinued... It was a skunkworx side project of FireFox and they eventually stopped supporting it and killed the script. The extended features were integrated into FireFox (long ago), but unfortunately that doesn't help for the scenario here I mention which is IE debugging in the Web Browser control. You can use older versions of Visual Studio (2017 and older) to connect to applications and use script debugging. See post here...

https://weblog.west-wind.com/posts/2017/Jul/06/JavaScript-Debugging-in-a-Web-Browser-Control-with-Visual-Studio


Rick Strahl
April 13, 2021

re: Taking the new Chromium WebView2 Control for a Spin in .NET - Part 1

@Rob - yes I've seen this. This is caused by a version mismatch - usually happens if you installed the WebView2 runtime, then uninstall it and some other version (perhaps from a Canary build) is used instead.

This is frustrating - had that issue and then it magically went away when I re-installed the WebView2 runtime explicitly.

Microsoft is working to get the WebView2 runtime installed with Windows updates. Once we have a few rounds of this in I think it'll be pretty safe to pick an older version and just stick with that and according to what they are shooting for that should continue to work (ie. forward compatible). We won't know until we see this in the wild though and it'll probably take a few update cycles before enough machines get these WebView2 runtime updates.

But roughly that is my plan - wait it out until the runtime becomes more integrated and then pick an older version and just stay with that.


manoj
April 13, 2021

re: Debugging the Web Browser Control with FireBug

Hi, For me not getting Firebug debug window ? Is it due to link added in javascript not valid now ? Anyone has the updated link ?