Recent Comments



Rick Strahl
Thursday

re: Bypassing IIS Error Messages in ASP.NET

@Ferhat - You can use Failed Request Tracing and Logging to provide more info on failures in IIS. Enable on the site or the entire server and look in the relevant log folders (\inetpub\logs\FailedReqLogFiles) for more info.


Ferhat
Thursday

re: Bypassing IIS Error Messages in ASP.NET

Thanks for the article. We have been trying to figure out why our new API was generating 500 errors after our deployment. Once we figure out IIS was intervening with the response, it was your article that allowed us to figure out what was actually going on and fix the issues. Thanks a lot, that issue was frustrating for us and we were able to fix it right away with your article.


David Elyk
Wednesday

re: Troubleshooting Windows Sleep Insomnia

Replying to @Jesse

I just ran across the same issue and finally tracked it down.

That Backup Scan is being run by windows task scheduler and if you try to make changes you will get a permission error even if you are running as Administrator.

Task Scheduler is set to run as SYSTEM, so you either have to grab ownership, make your changes, then set it back (I guess?) to SYSTEM.

-Or-

I installed Psexec.exe from Sysinternals and invoked Task Scheduler with it:

psexec -sid %windir%\system32\mmc.exe /s taskschd.msc

Then you can make changes and actually save them.

Task Scheduler Library > Microsoft > Windows > UpdateOrchestrator Click Properties > Click Conditions Tab

Now you can clear the Wake the Computer to run this task checkbox


Rick Strahl
Tuesday

re: ASP.NET Core IIS InProcess Hosting Issue in .NET Core 3.1

@Carlos - Sorry I don't know but that sounds like an assembly that's not getting copied to the output folder properly.


Lex Li
March 23, 2020

re: ASP.NET Core and CORS Gotchas

I doubt whoever reported issues with IIS/IIS Express has enabled Windows authentication, which blocks anonoymous preflight requests.

For IIS the out-of-band CORS module can ease the pains, but for IIS Express Microsoft didn't have an installer. So I wrote a few PowerShell scripts to help https://github.com/lextm/iisexpress-cors


Carlos
March 23, 2020

re: ASP.NET Core IIS InProcess Hosting Issue in .NET Core 3.1

Hello Rick, Thanks for the post. I am getting a similar error (500.0) but when I go to the event log I get: "Unable to find hostfxr directory at C:\dev\Repos\fina-resort-tax\src\ResortTax.Web.External\host\fxr". I am upgrading my project to .net core 3.0 from 2.2 and can't even run the application in Visual Studio 2019 v16.4.6. The application uses the Angular/dotnet template. Any hints will be appreciated. I've spent 2 days on this. Thank


Rick Strahl
March 23, 2020

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

@Lukas - you need to be an Administrator to do it so that's a problem if your app is not running as an Admin.


Lukas
March 21, 2020

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

Hi, Can i open the port programmatically in order to have a server that's accessable from outside out of the box?


Rick Strahl
March 19, 2020

re: Null API Responses and HTTP 204 Results in ASP.NET Core

@Dbsquared - Personally I feel like ASP.NET Core's behavior oversteps its bounds by doing this sort of fixup. It should default to the stock behavior which is to return raw data results, and set flags to override to more 'open to interpretation' behavior.

To me a 204 response makes no sense for an endpoint that can return a JSON result. A 204 response should be reserved for results that never return data (ie. void results).


Rick Strahl
March 19, 2020

re: Null API Responses and HTTP 204 Results in ASP.NET Core

@Dbsquared - That's open to interpretation. If you ask your server application handler to return a typed result from a JSON endpoint and then it doesn't that's just not right. What should Angular do in that case? Assume a 204 is null? That's not cool either. I think Angular could maybe do something different here but in my view the behavior is as I would expect it - I'm asking it to expect a typed result and the server didn't give it to me. If the result is a null JSON response, Angular works properly because that matches the signature of the HttpClient.


Rick Strahl
March 19, 2020

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

@Sebastian - there's nothing wrong with using the Console logger, if you don't log in info mode. That's because normal production error mode only writes out error info which hopefully should be infrequent. But if you have info logging going on you will slow down your app regardless of where stdout points or how the logger writes it out. It's obviously exaggerated by a high volume scenario where many threads are competing for the same log resource, but that's the point of this post.

The key is to make sure that logging only logs errors in production 😃


Jeremy
March 19, 2020

re: ASP.NET MVC Postbacks and HtmlHelper Controls ignoring Model Changes

Oh man, I just wasted hours on this and another quirk where you have to be careful what you name your action parameters. This model binder is a pain sometimes! Mahalo for this


Sebastian
March 19, 2020

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

I always use Console logger and the performance does not depend that much on the logger itself, but more how stdout is handled.

Yes, usually it is very slow, Powershell or Command Line are terribly slow. But not as terrible as in your micro benchmark. When your request has a total of 20ms compute time than the 0.2ms for logging does not matter that much. In real application the difference is not that big.

But more importantly it also depends on your deployment.

I think in IIS, the stdout is usually just discarded, but you can also forward stdout to a file.

In docker or kubernetes, stdout is forwarded to the logging driver, which is usually just a file. Then you can either use another logging driver or setup another container which reads the files and forwards the log entries to a logging system such as ElasticSearch. I use Google Cloud Engine and you get this for free there.

Btw: Stdout is also one of the principles of a 12-factor app: https://12factor.net/logs


Steve Pettifer
March 17, 2020

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

Just been bitten by this - somehow our default logging level block was removed from config so it defaulted to Information. Cue a crap ton of junk heading out to console and once deployed to AKS, that got piped straight to Log Analytics (we didn't realise it was doing that - our team and the team that manage our AKS instances had a mis communication!). turns out Log Analytics was costing more than the AKS resources. Oops.


Rob
March 14, 2020

re: Web Code is a solved Problem: How about fixing Web UI next?

An inexperienced developer will create hacks on hacks on hacks without solving underlying issues. A corporation will generally take the cheapest way forward shown the latest hack, it's still better than the competition after all. This is how browsers survive, this is how poor code survives, this is how poor script hackers can do this enough times to write a cv.

HTML was not the answer as soon as was conceived.

..back to X terminals.


Rich Ellis
March 13, 2020

re: Back to Basics: Rewriting a URL in ASP.NET Core

Good points. I agree the regex stuff gets annoying.

Forgetting to update web.config is something I would never do, what is being implied here? 😉


Rick Strahl
March 13, 2020

re: Back to Basics: Rewriting a URL in ASP.NET Core

@Rich - added a section at the end pointing at the ASP.NET Core Middleware. Thanks for the reminder.


Rick Strahl
March 13, 2020

re: Back to Basics: Rewriting a URL in ASP.NET Core

Yes the re-write Middleware can be used for setting up more full fledged rules and that's very useful.

This post is about one off rewrite operations. I find that in most cases having a whole rules engine is overkill if all you have a couple of URLs you need to rewrite. To me it's actually much cleaner to define rules in code instead of some special rule or regEx format with funky if/then logic 😃 But that makes good sense if you need to deal with lots of URLs and legit URL patterns. For one offs - not so much.

But then that behavior is tied to a specific platform

Yup, but it depends on what you're doing. If you're dealing with content that the front end Web server deals with (like Static Page handling or toplevel path routing) then definitely that has to be handled at the server level.

However, if you have application rewrites I would prefer to have them in app as opposed to on the server level. But these days with proper configuration pipelines that's probably less an issue then forgetting to add your re-write rules into a web.config 😃


Rich Ellis
March 13, 2020

re: Back to Basics: Rewriting a URL in ASP.NET Core

Doesn’t ASP.NET Core 3 (if not earlier) have a URL rewriting middleware package implicitly included?

What are your thoughts on where this kind of thing should ideally be handled? It’s reliable to set it up in the middleware chain, but I always cringe a little — it seems like this sort of thing ought to be dealt with in front of the app, like in IIS or nginx or whatever. But then that behavior is tied to a specific platform, and you lose the ability to push the app elsewhere without having to recreate it.


El barako
March 10, 2020

re: Working around the lack of dynamic DbProviderFactory loading in .NET Core

My issue is I am using an old ClassLibrary with the old DBProvider factories together with a MVC Core 3.1 UI.

I have to install the SQL Client dependency on the UI which really sucks.

Is there a way around this? or do I need upgrade the old class libraries?

The way our project are structured...

UI->ServiceFactory-Service->DAProviderFactory-DAProvider(MS,MYSQL)

I want to retain dependencies on the specific DAProviders?

However MVC requires me to reference the providers on the UI level.


Dbsquared
March 10, 2020

re: Null API Responses and HTTP 204 Results in ASP.NET Core

For the Angular issue, instead of doing the hack work around, shouldn't Angular fix the ability to handle a standard http response code? This seems more like an angular short fall than the API


Zea
March 10, 2020

re: A WebAPI Basic Authentication Authorization Filter

This article acts as if Authorization and Authentication are the same, and uses them interchangeably in almost every place, even in class names. It's not the same, it can't be treated the same, it shouldn't be called the same.


Rick Strahl
March 08, 2020

re: Troubleshooting Windows Sleep Insomnia

@Frank - that sounds nice but I don't have those sleep settings unfortunately. I merely see Sleep After and Hibernate After with times. No options for wake anything unfortunately.

Those used to be there, but apparently Microsoft has buried those even further away.


Rick Strahl
March 07, 2020

re: Building a Live Reload Middleware Component for ASP.NET Core

@Rick - Not sure about the Web Socket error. What browser? Make sure there's not a proxy in the way or some sort of blocking due to WebSockets being disabled in the browser. If possible try a different browser just to see if it's some config issue.

As to live reload and debug - you can't do both if you want to be able to auto-restart after server code changes. If you make a code change the server has to restart and if you were debugging it shuts down and the debugger along with it. So dotnet watch run manages the .NET code changes and auto-restarts.

For me the workflow typically is run dotnet watch run with making changes and live reload. The majority of code I work on doesn't need debugging and can be resolved by simply making quick code changes. If I really do need debugging, I just stop dotnet watch run and run the debugger from Visual Studio. You lose live reload but you get the deep debugging support. I do my debugging and when done, re-run dotnet watch run. I find I very rarely have to resort to using the debugger in this workflow.


Rick Piovesan
March 07, 2020

re: Building a Live Reload Middleware Component for ASP.NET Core

and btw does this technique mean its not possible to debug server side code (step thru, breakpoints, etc) since seems not possible to F5 launch the site while 'dotnet watch run' is active?


Rick Piovesan
March 07, 2020

re: Building a Live Reload Middleware Component for ASP.NET Core

Hi, thought to try this out: New VS 2019 Asp.Net Core 3.1 web app, with identity (local user); installed as described above; launched watcher; (didn't realize I didn't need to / and should not / actually run (F5) the site!); anyhow launch browser to site "https://localhost:5001/"; browser gets continuous error "WebSocket connection to 'ws://localhost:5000/__livereload' failed: Error during WebSocket handshake: Unexpected response code: 307" any ideas?


Frank
March 06, 2020

re: Troubleshooting Windows Sleep Insomnia

Thanks for a great article, I also struggled with insomnia issues on my Windows 10 when attempting to sleep. On my system, there was also a couple of wake timers active.

To turn them off completely, you can

  1. Open the Control Panel.
  2. Click on "Power Options" and select "Change Plan Settings" for the power plan that is in use.
  3. Click on "Change Advanced Power Settings" and expand "Sleep".
  4. Expand "Allow Wake Timers" and disable it.

NicolaB
March 05, 2020

re: Bootstrap Modal Dialog showing under Modal Background

@Abdou, good but... not good enough. If you use modal-dialog-centered it doesn't work.

Better so:

.modal-backdrop { /* bug fix - no overlay */
    display: none;
}

.modal-content {
    box-shadow: 0px 0px 00px 1500px #00000085;
}

André Cardoso
March 05, 2020

re: Troubleshooting Windows Sleep Insomnia

I got into the habit of hibernating the laptop for the night/weekend (and having it eat disk for hibernating)… But since a few months whenever I hibernate it, the next morning I lose my 3 monitors configuration (it's all Dell) and have to resort to disabling and enabling the Graphics card: Get-PnpDevice| where {$_.friendlyname -like "IntelHD Graphics"} | Disable-PnpDevice -Confirm:$false


Jesse Slicer
March 04, 2020

re: Troubleshooting Windows Sleep Insomnia

My only one left is TASKS\Microsoft\Windows\UpdateOrchestrator\Backup Scan and nothing I seem to do can touch that task. I hope the other ones I was able to shut off solve the problem. Thanks for all the great info!


Alexandre Jobin
March 04, 2020

re: Troubleshooting Windows Sleep Insomnia

Thank you for your article. I do have this problem on all my laptops and I burned the screen of my last one because it stayed on the login screen all the week-end.

I will try the commands that you have suggested for sure.


Haydn
March 04, 2020

re: Web Browser Control & Specifying the IE Version

I created this basic web page that tells you what compatibility mode IE is running in: https://documentmode.000webhostapp.com

This was helpful for finding out if Rick's registry solution worked for a WPF application I have no control over. And it did, thank you Rick!


Alex Sarafian
March 04, 2020

re: Troubleshooting Windows Sleep Insomnia

I had a similar issue in the past when Microsoft was much more aggressive on their Windows updates policies.

It turns out that a job is created to restart the computer to make sure that it can apply the updates. Even when disabling, the system will at some point create it again. So I had to create a schedule job to disable the job that shows up now and then. I think now Microsoft is less aggressive with the job re-creation but it still happens. My setup is a desktop machine and if something like this happened on my laptops I would be annoyed. But the professional laptops I worked with I never had such issues. Maybe the policy differs between desktop and laptops although the lines are becoming grey.

More on this if you are interested here. I hope this also helps others.


Rick Strahl
March 03, 2020

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

@zuhry - the content is always the same. How it's handled in your action method depends on the way you specify the parameters (ie. [FromBody] vs. not).


zuhry
March 03, 2020

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

how to check if content from body or from form?


Anders Gustafson
March 01, 2020

re: Flexbox Containers, PRE tags and managing Overflow

Many thanks Rick for documenting this issue. I ran into the same problem when starting to use Flexbox layout, and your solution seems to solve it.


Dave Black
February 28, 2020

re: Creating a dynamic, extensible C# Expando Object

Hi Rick,

I'm using Dynamics for working with a CMS (Storyblok). Each Content entry is defined as a "story". There are a few well-defined properties on each "story", but the rest are dynamic based on how the content editors define and create a "story".

{
  "story": {
    "id": 107350,
    "name": "My third post",
    "slug": "my-third-post",
    "content": {
      "component": "your_content_type",
      // and fields you define yourself are in here
    },
    ...

I have a simple POCO defined to use with JSON serialization to work with the values on the back-end:

    public class StoryblokDTO
    {
        public int id { get; set; }
        public string name { get; set; }
        public string slug { get; set; }
        public StoryblokContentDTO content { get; set; }
        //public dynamic content { get; set; }
    }

    public class StoryblokContentDTO : DynamicObject
    {
        public string component { get; set; }
        // elided for brevity

However, I have to cast the content property to dynamic anytime I access "dynamic properties at compile-time. Otherwise, I get compilation errors.

For example, the following does not work (compile errors):

    private static int SortResultsPrimary(StoryblokStoryDTO dto)
    {
        // 'search_priority' is a dynamic property
        // compile error on line below
        if (dto.content?.search_priority == null)
        {
            return 0;
        }

        // compile error on line below
        Int32.TryParse(dto.content.search_priority.ToString(), out int value);
        return value;
    }

But this works if I cast or explicitly treat the property as dynamic:

    private static int SortResultsPrimary(StoryblokStoryDTO dto)
    {
        dynamic content = dto?.content;
        // 'search_priority' is a dynamic property
        if (content?.search_priority == null)
        {
            return 0;
        }

        Int32.TryParse(content.search_priority.ToString(), out int value);
        return value;
    }

I'm surprised that the compiler doesn't seem to recognize that my instance is derived from DynamicObject and let me access the dynamic properties without casting or explicitly calling out the property as dynamic. Do you have any idea why this is?


Rick Strahl
February 28, 2020

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

@Peter - hmmm that's odd. Just tried custom config in a 3.1 app and that code works for me without issue. You need Microsoft.Extensions.Configuration and IConfiguration injected, but I think new projects do that by default now.


Peter Kellner
February 28, 2020

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

As always, thanks for this article. so much easier to add logging then what is on docs.microsoft.com (Sorry Steve).

With core 3.1, this doesn't compile anymore: config.AddConfiguration(Configuration.GetSection("Logging")); (can not resolve symbol Config) Thoughts? (love breaking changes)

How's your immune system Rick?


anonymous
February 27, 2020

re: WCF WS-Security and WSE Nonce Authentication

Hey,

Thanks this instructive article.I have applied this steps and i see the security section but messageId,to,action parameters is gone now. I think, it's related the "MessageSecurityVersion" on the binding. How can i create action,to,messageId parameters with security node in the header?


mky
February 27, 2020

re: Dealing with Anti-Virus False Positives

Most AVs these days use machine learning for detecting malware. So what you're observing is a poorly "trained" neural network that fires false positives on partial matches with other malware. And since no-one really understands how exactly those neural networks "do their thing", if someone somewhere used that commercial MSI packager to create an actual malware, for those particular (lesser known) Chinese AVs your installer also "looked like" a virus. Thus you got your false positives.

And I hear you, yes, that is VERY annoying!


Rick Strahl
February 26, 2020

re: Live Reloading Server And Client Side ASP.NET Core Apps

@Rian - also check out the follow up article that provides another native solution that works as middleware

Building Live Reload Middleware for ASP.NET Core


Rian Katoen
February 26, 2020

re: Live Reloading Server And Client Side ASP.NET Core Apps

Thanks for the tutorial, after some tweaking I've got this up and running and it works as expected. Can't wait for hot reloading to be added natively in Blazor as to not have to recompile every time...

One addition: On W10 it browser-sync needs to be adjusted a bit. The --files options accepts an array and not a list of space seperated strings according to the documentation. I've adjusted this by splitting the file filters.

Instead of using:
browser-sync start --proxy http://localhost:5000/ --files 'browsersync-update.txt **/*.css'

I used this:
browser-sync start --proxy http://localhost:5000/ --files 'browsersync-update.txt' '**/*.css'


Rick Strahl
February 26, 2020

re: Web Browser Control & Specifying the IE Version

@Andrew - not sure if CHtmlView uses IE Web Browser control but would imagine so. You don't need to reboot, but you have to restart the application.


Marek Ištvánek
February 26, 2020

re: WPF Bindings and CurrentCulture Formatting

I hit the problem of CultureInfo.Current(UI)Culture resetting back after my change again in our localization .NET Standard code used in WPF/UWP/... The cultures are changed on main (UI) thread with our SetCulture method, but resetted back after a while by the framework. After adding second call of SetCulture method with UI SynchronizationContext.Post just after the first direct one, cultures are kept and not resetting back occures again. Tested only in WPF.


Mike
February 25, 2020

re: Using plUpload to upload Files with ASP.NET

in the plUploadBaseHandler should the check for the allowed file extensions happen earlier. If there are no chunks then it looks like the file extension is not being checked.


Rick Strahl
February 24, 2020

re: Null API Responses and HTTP 204 Results in ASP.NET Core

@Lycas - yup definitely true. But that forces you into returning IActionResult results rather than strongly typed values. That has consequences like not being able to easily use Swagger. Personally I prefer using raw result types for API endpoints just because it's cleaner and easier to test as well.

But definitely true - it's an option to explicitly force a response type. I think I didn't mention that in the old post either and probably should be mentioned. Thanks!


Lycas
February 24, 2020

re: Null API Responses and HTTP 204 Results in ASP.NET Core

Hey, Rick! Long-time lurker here.

You can use Controller.Json() to create a JsonResult, letting ASP.NET Core that you want to return json. For example, this code will return the valid json string null as a response and set the correct content type:

public IActionResult Null()
{
    return Json(null);
}

In your example, you can wrap the ResponseResult in a JsonResult and it will do the right thing if it happens to be null:

public IActionResult MayBeNull()
{
    ResponseResult? result = GetResult();
    return Json(result);
}

Rick Strahl
February 24, 2020

re: Building a Live Reload Middleware Component for ASP.NET Core

@Patrick - I don't think you'd want that. The CSS needs to go into the right place in the page, and then it would also compete with the old CSS. Does it go before? After?

I think it's reasonable to reload the page.

Scripts are even worse since code will have already run. Somethings need to run in a script at startup of the page which is now already loaded. So many scenarios that make this problematic.


Patrick Szalapski
February 24, 2020

re: Building a Live Reload Middleware Component for ASP.NET Core

Hi Rick, thanks for this middleware.

It appears that, on a .css change, this approach reloads the page. Is there any way to get it to inject the new styles as a DOM change rather than reloading the page? I suppose the same could be true for a .js change, too.