Subscribe: Rick Strahl's Web Log
Added By: Feedage Forager Feedage Grade B rated
Language: English
api  apierror  application  applications  context  core net  core  describe  error  exception  iis  net core  net  web  windows 
Rate this Feed
Rate this feedRate this feedRate this feedRate this feedRate this feed
Rate this feed 1 starRate this feed 2 starRate this feed 3 starRate this feed 4 starRate this feed 5 star

Comments (0)

Feed Details and Statistics Feed Statistics
Preview: Rick Strahl's Web Log

Rick Strahl's Web Log

Life, Surf, Code and everything in between


Error Handling and ExceptionFilter Dependency Injection for ASP.NET Core APIs

Mon, 17 Oct 2016 06:14:05 GMT

While working on my ASP.NET Core API and Angular 2.0 AlbumViewer sample, one last thing I need to round out the feature set is to make sure that consistent error results are returned to the client. Unhandled errors should also be logged to disk for later reference. ASP.NET Core does not provide a consistent error response for API errors out of the box. In fact, an error in an API results in the same error result as any other type controller result - an HTML error page (which you can configure) or nothing at all if you don't hook up any error handling middleware. For API's this is generally useless - a client application expecting a JSON result is not going to be able to do anything useful with an HTML error page, so some extra work implementing an ExceptionFilter is required. Actually there are a several ways you can implement error handling but ExceptionFilters are amongst the easiest and most flexible to implement. Other alternatives might include custom middleware but I won't cover that in this post. ASP.NET Core also does not include a built-in file logging service so I have to rely on the excellent 3rd Party Serilog library to provide file logging for me. Additionally getting a logging dependency into a filter via Dependency Injection requires a little extra work. In this post I describe how to create an ExceptionFilter to create consistent API error responses and use a Dependency Injected logging provider. In the process I'll talk a bit about error handling in my API implementation. API Error Handling - A Use Case for an ExceptionFilter In my AlbumViewer API I capture all errors using an MVC ExceptionFilter. As you might remember from previous posts, in ASP.NET Core MVC and APIs share a common processing pipeline so any filters you create can be used by both MVC and API controllers. In this case the controller will be specific to API results. Inside of my API code any unhandled Exception should trigger the ExceptionFilter, which then captures the exception and in response returns a JSON error response in the form of a standard error object. The idea is that any error I can possibly intercept will be returned as a JSON response so that the client can provide some meaningful error information. The object returned always has a .message property that can that can potentially be used to display error information in a front end. To start with, here is my initial error filter implementation without any logging: public class ApiExceptionFilter : ExceptionFilterAttribute { public override void OnException(ExceptionContext context) { ApiError apiError = null; if (context.Exception is ApiException) { // handle explicit 'known' API errors var ex = context.Exception as ApiException; context.Exception = null; apiError = new ApiError(ex.Message); apiError.errors = ex.Errors; context.HttpContext.Response.StatusCode = ex.StatusCode; } else if (context.Exception is UnauthorizedAccessException) { apiError = new ApiError("Unauthorized Access"); context.HttpContext.Response.StatusCode = 401; // handle logging here } else { // Unhandled errors #if !DEBUG var msg = "An unhandled error occurred."; string stack = null; #else var msg = context.Exception.GetBaseException().Message; string stack = context.Exception.StackTrace; #endif apiError = new ApiError(msg); apiError.detail = stack; context.HttpContext.Response.StatusCode = 500; // handle logging here } // always return a JSON result context.Result = new JsonResult(apiError); base.OnException(context); } } The exception filter differentiates between several different exception types. First it looks at a custom ApiException type, which is a special applica[...]

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

Thu, 29 Sep 2016 01:19:50 GMT

Recently I needed to connect to my Windows based ASP.NET Core API from my Mac and in order for that to work some configuration settings are necesary so that the ASP.NET applications can serve HTTP content to the external network connection that this entails. In this post I show what you have to do to enable remote connections both using the Kestrel and IIS Express Web servers.(image)

ASP.NET Core and CORS Gotchas

Mon, 26 Sep 2016 21:34:08 GMT

CORS is a requirement for cross domain XHR calls, and when you use Angular 2.0 default dev server and talk to an ASP.NET Core application you'll need to use CORS to get XHR to talk across the domain boundaries. Here's how to set up CORS and how to test it.(image)

Bootstrap Modal Dialog showing under Modal Background

Wed, 14 Sep 2016 17:42:32 GMT

On more than a few occasions I've run into issues with Bootstrap's Modal dialog rendering incorrectly with the dialog showing underneath the overlay. There are a number of ways around this problem, but none of them are universal that depend on how your pages are laid out. It's especially problematic for applications that dynamically render components where there's no good control on where the elements are placed outside of the components DOM containership. In this post, I describe a few of the workarounds and their limitations.(image)

External JavaScript dependencies in Typescript and Angular 2

Mon, 12 Sep 2016 08:21:30 GMT

Angular 2.0 and Typescript make it very easy to import external Typescript classes and references using the module loading functionality built into Typescript (and ES6). However, if you need to work with external libraries that aren't built with Typescript you need to do a little extra work in importing and referencing the external libraries. In this post I show two approaches for importing libraries as modules and dereferencing library globals so that the Typescript compiler is happy.(image)

Capturing Zoom Operations in the WPF Web Browser Control

Tue, 06 Sep 2016 01:55:14 GMT

If you need to capture Zoom operations in the Web Browser control - either to avoid letting hte user zoom or to capture the zoom operation and take action on it - you need to dig into the Web Browser's DOM events to capture the scroll wheel and key events. In this post I describe how you can do just that by looking at an application that captures scrolling and rather than zooming adjusts the font size of the content.(image)

Detecting and Setting Zoom Level in the WPF WebBrowser Control

Mon, 22 Aug 2016 07:25:01 GMT

Zoom level detection in the Web Browser control is a pain and in this article I describe one approach I used to both capture the current Zoom level in order to adjust font sizes, and then also explicitly set the Zoom level in the Web Browser control of a WPF application.(image)

Moving to Lets Encrypt SSL Certificates

Sat, 09 Jul 2016 19:18:32 GMT

This week marks the expiration of my last paid for SSL certificates and moving all certificates to Lets Encrypt. In the process I had a chance to moving some of my smaller personal and hobby sites as well as moving my wildcard cert for the main site. In this post I'll describe the process I'll describe what tools I used and the process I went through to gradually move my sites over to Lets Encrypt.(image)

First Steps: Exploring .NET Core and ASP.NET Core

Wed, 29 Jun 2016 23:30:51 GMT

In this post I'll demonstrate how to get started with .NET Core and ASP.NET using the Command Line Tools. I'll create a few very simple projects and starting with a plain console application, show how to hook up ASP.NET, run an API and MVC app and then run the app locally on Windows and then move it over to run on the Mac. This is not meant to be your typical getting started tutorial that jumps right into Visual Studio and creating a Web project from there. Rather, the purpose of this post is to demonstrate some of the core underpinnings of how .NET Core and ASP.NET Core projects are bootstrapped to run.(image)

ASP.NET Web Site Project Publishing and Changing ACLs

Wed, 29 Jun 2016 06:02:01 GMT

When publishing ASP.NET Web Site Projects, the project publish will overwrite server ACLs by clearing them to the inherited defaults and removing rights from common accounts. The result is that if you have custom ACLs set on the server they will be wiped by default. This occurs only on Web Site projects and in this post I remind myself of the .pubxml override setting that disables this default behavior(image)

Upgrading to ASP.NET Core RTM from RC2

Mon, 27 Jun 2016 19:04:29 GMT

I installed and upgraded an ASP.NET Core Sample application today and while the actual project upgrade process from RC2 was relatively easy, there were a few hiccups with installation and one of the breaking changes for the RTM release. In this post I'll go over some of the things I ran into and the workarounds.(image)

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

Fri, 24 Jun 2016 02:34:39 GMT

Managing SSL certificates on Windows has always been a pain in the ass and recently with the introduction of SNI to support multiple SSL certificates per site things have changed slightly in order to register certificates with IIS programmatically. In this post I show how to use PowerShell and the IIS WebAdministration snap in commands to create or import and register an SSL Certificate via the Command Line along with how this convoluted process works(image)

ASP.NET Core and .NET Core Overview

Mon, 13 Jun 2016 16:06:52 GMT

ASP.NET Core and .NET Core are almost here, with the RTM release scheduled for the end of this month. In this post I’m going to revisit the high level overview architecture of .NET Core and ASP.NET Core since so much has changed, to help you understand how the pieces fit together and what it means to develop on the new stack along with some personal thoughts on how I plan to approach all of this new tech in my own work.(image)

Publishing and Running ASP.NET Core Applications with IIS

Mon, 06 Jun 2016 08:19:08 GMT

If you plan on hosting ASP.NET Core applications on IIS, you'll find that the process to get your application to run is quite different than it was with classic ASP.NET. Because ASP.NET Core applications are essentially standalone Console applications that run outside of IIS, some special tooling and new publishing tools are required to get your apps up and running on Windows Server. In this post I'll give an overview of the architecture and show you how to deploy your ASP.NET Core applications using IIS on Windows Server.(image)

IIS Channel Listener Errors in Windows 10 Insider Build 14342

Mon, 30 May 2016 21:17:27 GMT

After installing Insider Build 14342 I ran into some major issues with IIS crashing hard and resulting in stopped Application Pools. After some tracking it turns out this is due to application pool bitness which causes 32 bit Application Pools to crash for me.(image)

Windows Updates and Lost Software Licenses and Activations

Mon, 30 May 2016 03:27:50 GMT

Windows Updates often hose Software Activations and Licenses for various commercial software packages. It's a pain in the ass and it's time to let those vendors that use the outdated practice of counting activations based on Windows OS criteria is no longer viable.(image)

Strongly Typed Configuration Settings in ASP.NET Core

Mon, 23 May 2016 07:42:45 GMT

ASP.NET Core provides built-in support for using strongly typed classes to represent configuration information. The configuration system provides a flexible mechanism for using different configuration storage providers and mapping those providers to your strongly typed objects. In this post I show how to set up strongly typed resources and use them in your ASP.NET Web applications.(image)

Using Westwind.Globalization to edit loose RESX Files

Wed, 18 May 2016 17:32:54 GMT

Although Westwind.Globalization is primarily aimed at Web applications, you can also use it to edit arbitrary RESX files using the Localization Administration interface that comes with the library. In this post I show how you can import RESX resources, then use the editor to manipulate RESX resources interactively, and then export the resources back out, using a local Web application on your machine.(image)

Creating Single Instance WPF Applications that open multiple Files

Fri, 13 May 2016 09:34:20 GMT

If you're building document centric applications, Singleton style EXE applications are pretty common. Rather than creating new windows for each opened file, a more common scenario is to open new tabs in a single instance. In this post I'll describe how to create a WPF application that allows only a single instance to run and passes command line arguments passed in secondary instances to the primary instance and I'll describe some pitfalls that you might have to watch out for.(image)

Getting 'motivated' to move to SSL and HTTPS

Mon, 09 May 2016 20:43:28 GMT

The pressure is on: HTTPS is pushed front and center more and more as we see the browser vendors and API tools providers, making SSL encryption no longer an optional part for many things that you build on the Web. SSL and HTTPS are becoming a requirement and for good reasons. I personally ran into this with the Google Maps API in one of my applications that now requires an HTTPS based client page in order to use this API. In this post I discuss some of the issues and why this is actually a good thing, and some of the steps I took to move my existing site to HTTPS.(image)

Windows 10 Bash Shell Network Connectivity not working?

Wed, 13 Apr 2016 19:41:53 GMT

When trying out the Windows 10 Bash on Ubuntu shell, I ran into several problems with networking. Turns out that there are issues with IPv6 and by swapping or removing the IPv6 nameserver entries with IPv4 versions connectivity can be restored back.(image)

Google AdSense for AJAX Content

Sat, 09 Apr 2016 07:39:33 GMT

I recently redesigned one of my Web sites to use dynamic page re-loading for additional page content, which broke the original AdSense ad code. In this post I'll describe how to get AdSense ads to work with AJAX loaded content by explicitly calling Googles ad code from your dynamic navigation code.(image)

Configuring ASP.NET and IIS Request Length for POST Data

Wed, 06 Apr 2016 07:05:19 GMT

One of the most infuriating things about IIS configuration in general is how the Request length is configured in the IIS and ASP.NET. There are several places that control how much content you can send to the server and over the years this setting has changed in a number of ways. The places where it's configured is not super obvious and they can be fluid because some of these features are...(image)

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

Sat, 02 Apr 2016 07:55:59 GMT

Over the last few days I've been fighting with a Web Service that does not allow inline namespaces which WCF copiously uses by default in its generated service proxies. In this post I describe how to create a custom message formatter add namespaces explictly to the SOAP envelope.(image)