Global exception handling in ASP.NET Web API 2.1 with NLog? - c#

ASP.NET Web API 2.1 includes a new global error handling capability. I found an example that demonstrates how to log exceptions into ELMAH. But I use NLog to log errors to a database table. Is it possible to use Web API global error handling with NLog? If so, please provide an example.

It's actually quite simple, you either implement IExceptionLogger by hand or inherit from the base class, ExceptionLogger.
public class NLogExceptionLogger : ExceptionLogger
{
private static readonly Logger Nlog = LogManager.GetCurrentClassLogger();
public override void Log(ExceptionLoggerContext context)
{
Nlog.LogException(LogLevel.Error, RequestToString(context.Request), context.Exception);
}
private static string RequestToString(HttpRequestMessage request)
{
var message = new StringBuilder();
if (request.Method != null)
message.Append(request.Method);
if (request.RequestUri != null)
message.Append(" ").Append(request.RequestUri);
return message.ToString();
}
}
Also add it to the config:
var config = new HttpConfiguration();
config.Services.Add(typeof(IExceptionLogger), new NLogExceptionLogger());
You can find full sample solution here.

Other thing that might be handy WebApiContrib.Tracing.NLog package that allows you to use ITraceWriter interface to output to logs with NLog. A cool thing about ITraceWriter is that "all traces can correlate to the single request that caused that code to run (see this link)

Related

How to fix 500 Internal Server Error for POST integration tests using TestServer and Antiforgery? ASP.NET Core

I've got a working ASP.NET Core 2.2 implementation that utilizes both MVC and API controllers, and I'm putting together an integration test project to cover everything that has already been tested manually - the basic crud, mostly. Everything works except the tests that use PostAsync to POST data. These tests always get a 500 Internal Server Error as a response from the client, and I cannot for the life of me figure out why. Oi!
The TestServer setup is a pretty standard approach that I've seen on many different blogs and articles. A TestStartup class extends the standard Startup, and overrides the configuration to use in-memory database with seed data. My test fixture base then uses the TestStartup to create a server, and a client, and has a method, which I know works fine, to extract the antiforgery token and add it to forms and headers. All other tests verifying all other aspects of CRUD are working, proving that the seeded data can be retrieved, via both MVC and API calls.
The POST calls that eventually fail with a 500 Internal Server Error do make it into the controller, and the subsequent repository, just fine. With all these aspects in place, I've yet to be able to see the source of the 500.
[Fact]
public async void CreatePost_ShouldReturnViewWithNewlyCreatedLabelData()
{
// Arrange
var formData = await EnsureAntiForgeryTokenOnForm(new Dictionary<string, string>()
{
{ "Name", TestDataGraph.Labels.LabelNew.Name },
{ "WebsiteUrl", TestDataGraph.Labels.LabelNew.WebsiteUrl }
});
// Act
var response = await Client.PostAsync("/labels/create", new FormUrlEncodedContent(formData));
// Assert
Assert.Equal(HttpStatusCode.Found, response.StatusCode);
Assert.Equal("/Labels", response.Headers.Location.ToString());
}
This is a simple example test in Xunit that attempts to validate the creation of a new simple object, type Label, via MVC route, which follows the standard path format, having been scaffolded. This test will make it into the controller, and its repository, but the response will be a 500 Internal Server Error.
Could I have missed something important in Startup? Any ideas for finding further details about this failure? Thanks in advance! I can post more code or details if they will be helpful.
Try adding trace logging... Trace logging will display activity in the .Net Core framework.
...
public static ILogger<ConsoleLoggerProvider> AppLogger = null;
public static ILoggerFactory loggerFactory = null;
//
public void ConfigureServices(IServiceCollection services)
{
services.AddLogging(builder => builder
.AddConsole()
.AddFilter(level => level >= LogLevel.Trace)
);
loggerFactory = services.BuildServiceProvider().GetService<ILoggerFactory>();
AppLogger = loggerFactory.CreateLogger<ConsoleLoggerProvider>();
...
An example trace log:
trce: Microsoft.AspNetCore.Mvc.Razor.Internal.RazorViewCompiler[7]
Could not find a file for view at path '/Views/Home/_Layout.cshtml'.
After you have resolved the issue, change the LogLevel to a more appropriate value.

Exposing hangfire without auth

Is there a way to expose Hangfire in IIS without having to configure authorization?
In this specific case the dashboard should be open, but when accessing it (not in debug) it returns a 401 code.
I think you should be able to write a custom implementation of IDashboardAuthorizationFilter as described in the documentation. Be aware that the default is only local requests to the dashboard are allowed. It's also recommended that you really use authorization and do not publish unauthorized dashboards as it contains sensitive information.
If you still want to do it, try:
Custom DashboardAuthorizationFilter
public class MyAuthorizationFilter : IDashboardAuthorizationFilter
{
public bool Authorize(DashboardContext context)
{
return true;
}
}
Use it in the configuration of hangfire
app.UseHangfireDashboard("/hangfire", new DashboardOptions
{
Authorization = new [] { new MyAuthorizationFilter() }
});

Define NServiceBus instance-mapping in code

I'm writing an asp.net core application and wanna send a message to an NServiceBus endpoint.
As we have different environments I need to configure an endpoint address for each environment. I do that in the app settings.Env.json.
I like to do the same with the instance mappings. The only ways I know is to have a different instance-mapping.xml file for every environment or add it to the app.config that I don't have. Is there a way to set the instance machine in code? I don't wanna have different XML files.
I use NServiceBus 6.3.4
I added a feature to the endpoint configuration:
endpointConfiguration.EnableFeature<MyFeature>();
public class MyFeature : Feature
{
protected override void Setup(FeatureConfigurationContext context)
{
var endpointInstances = context.Settings.Get<EndpointInstances>();
endpointInstances.AddOrReplaceInstances("InstanceMapping",
new List<EndpointInstance>
{
new EndpointInstance("MyEndpoint").AtMachine("VM-1")
});
}
}
Check docs here and here

Global Error Handling in ASP.NET Web API 2

Preamble: This question is different from "Exception Handling in ASP.net Web API" as the OP was looking for custom Error Handling, not global handling. It also differs from other earlier questions that were answered, as those were for earlier versions of Web API, not version 2. Also note I am going to self answer this question. It took quite some searching to find the correct answer.
The question is: How do I globally handle errors in Web API 2.0? The error handling I have set up for MVC does not get activated for web api calls and I need to generically handle any error that is thrown so that relevant error information is returned to the client.
Global Error handling is correctly answered in this asp.net article. However the articles is missing a few important points to make the code actually work.
The article covers the details, but here it is in a nutshell:
Global Error Handling is already included in System.Web.Http.ExceptionHandling The classes in the article are already in this library, so there is no need to rewrite them.
The only class you need to write is the one which is customized for your app. In the article, they call it the "OopsExceptionHandler" However, the one written in the article does not compile. This is the updated code that does work:
public class OopsExceptionHandler : ExceptionHandler
{
public override void Handle(ExceptionHandlerContext context)
{
context.Result = new TextPlainErrorResult
{
//If you want to return the actual error message
//Content = context.Exception.Message
Request = context.ExceptionContext.Request,
Content = "Oops! Sorry! Something went wrong." +
"Please contact support#contoso.com so we can try to fix it."
};
}
private class TextPlainErrorResult : IHttpActionResult
{
public HttpRequestMessage Request { get; set; }
public string Content { get; set; }
public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
{
HttpResponseMessage response =
new HttpResponseMessage(HttpStatusCode.InternalServerError);
response.Content = new StringContent(Content);
response.RequestMessage = Request;
return Task.FromResult(response);
}
}
}
You then need to register the ExceptionHandler. An example of this is not given in the article, so here it is:
config.Services.Replace(typeof(IExceptionHandler), new OopsExceptionHandler());
This line goes in the WebApiConfig file, in the register method. Note that it is using 'Replace' not 'Add' as it will error out on Add. Only one is allowed by the framework.
That is all that is required. To test, throw an error from your web API and you will see the error message returned as the content of the webAPI call. Note that there are security implications to returning error messages to the client, so make sure this is what you really want.

Web Api - Request Parameters Outside Controller

I'm working on a ASP.NET Web Api project and made it accept version information in the url.
For example:
api/v1/MyController api/v2/MyController
Now I would like to get the request version v1, v2 inside a custom LayoutRenderer for Nlog. Normally I would do this like the below example.
[LayoutRenderer("Version")]
public class VersionLayoutRenderer : LayoutRenderer
{
protected override void Append(System.Text.StringBuilder builder, NLog.LogEventInfo logEvent)
{
var version = HttpContext.Current.Request.RequestContext.RouteData.Values["Version"];
builder.Append(version);
}
}
The problem: HttpContext.Current is NULL
I believe this is because I use Async wrappers for NLog and some calls before the Logger are also Async.
A example of the logger being called Async inside Ninject.Extensions.WebApi.UsageLogger. At this point the HttpRequestMessage has all info we need to get the Version.
/// <summary>
/// Initializes a new instance of the <see cref="UsageHandler" /> class.
/// </summary>
public UsageHandler()
{
var kernel = new StandardKernel();
var logfactory = kernel.Get<ILoggerFactory>();
this.Log = logfactory.GetCurrentClassLogger();
}
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
var startTime = DateTime.Now;
// Log request
await request.Content.ReadAsStringAsync().ContinueWith(c =>
{
this.Log.Info("{0}: {1} called from {2}", request.Method, HttpUtility.UrlDecode(request.RequestUri.AbsoluteUri), ((HttpContextBase)request.Properties["MS_HttpContext"]).Request.UserHostAddress);
this.Log.Info("Content-Type: {0}, Content-Length: {1}", request.Content.Headers.ContentType != null ? request.Content.Headers.ContentType.MediaType : string.Empty, request.Content.Headers.ContentLength);
this.Log.Info("Accept-Encoding: {0}, Accept-Charset: {1}, Accept-Language: {2}", request.Headers.AcceptEncoding, request.Headers.AcceptCharset, request.Headers.AcceptLanguage);
if (!string.IsNullOrEmpty(c.Result))
{
if (this.MaxContentLength > 0 && c.Result.Length > this.MaxContentLength)
{
this.Log.Info("Data: {0}", HttpUtility.UrlDecode(c.Result).Substring(0, this.MaxContentLength - 1));
}
else
{
this.Log.Info("Data: {0}", HttpUtility.UrlDecode(c.Result));
}
}
});
var response = await base.SendAsync(request, cancellationToken);
// Log the error if it returned an error
if (!response.IsSuccessStatusCode)
{
this.Log.Error(response.Content.ReadAsStringAsync().Result);
}
// Log performance
this.Log.Info("Request processing time: " + DateTime.Now.Subtract(startTime).TotalSeconds + "s");
return response;
}
The question
What would be the best way to make the VersionLayoutRenderer work in a generic way? Could I add a MessageHandler and Bind the HttpRequest to some Async scope? If so any guidelines would be much appreciated cause I'm still getting used to Ninject.
For the time being I add the version information directly to the Log Call in the UsageHandler, but I would really like a more generic solution, where I can always rely on version information inside my logging.
Edit: Updated the question to be more specific and included more details.
Try injecting the context using something like:
kernel.Bind<IDependency>()
.To<Mydependency>()
.InRequestScope()
.WithConstructorArgument("context",c=>HttpContext.Current);
The actual issue is really neutral wrt what you should do with Ninject - you just need to get the phasing of your processing such that any objects that are going be running async have everything they need without relying on the magic HttpContext.Current. Get that working with no DI Container first.
Then, to use Ninject the major steps are:-
Your Bind statements need to be run once. See the Ninject.MV3 wiki for the best approach (until it gets merged in, there is not OOTB with the NuGet-based edition)
as #rickythefox (+1'd) says, your registration should bake the thread/context-relative data into the object and you config the registration such that it can happen early in request processing, when you're still on the thread that's HttpContext.Current
kernel.Bind<ILogger>()
// TODO replace GCCL with something like GetClassLogger(ctx.Request.Service.ReflectedType) - see the wiki for examples
.ToMethod( ctx=> ctx.Get<ILoggerFactory>().GetCurrentClassLogger())
.InRequestScope()
.WithConstructorArgument("context",c=>HttpContext.Current);
Then just make the constructor of the handler take a ILogger, which can be assigned to .Log (which I hope isnt static :D)
NB, the aim is for you never to write a kernel.Get(), ever, period.
The real problem here though, is that proper use of WebApi does not involve using HttpContext.Current or any other magic static methods or anything similar (for testability, to make yourself independent of the hosting context (self hosting, OWIN etc), and many more reasons).
Also, if you are using NLog (or Log4Net) you should also look at the Ninject.Extensions.Logging package (and source).
The GlobalConfiguration class can provide you access to the routing configuration.
// The code below assumes a map routing convention of api/{version}/{controller}/....
// This will give you the configured routes
var routes = GlobalConfiguration.Configuration.Routes;
// This will give you the route templates
var templates = routes
.Select(route => route.RouteTemplate);
// This will give you the distinct versions for all controllers
var versions = routes
.Select(route => route.RouteTemplate)
.Select(template => template.Split("/".ToCharArray(), StringSplitOptions.RemoveEmptyEntries))
.Select(values => values[1])
.Distinct();
// This will give you the distinct versions for a controller with the specified name
var name = "MyController";
var controllerVersions = routes
.Select(route => route.RouteTemplate)
.Select(template => template.Split("/".ToCharArray(), StringSplitOptions.RemoveEmptyEntries))
.Where(values => String.Equals(values[2], name, StringComparison.OrdinalIgnoreCase))
.Select(values => values[1])
.Distinct();
I am not sure if you are trying to resolve the version with a known value (the name of the controller) or if you are trying to dynamically resolve it. If you inject the current HttpContext, you can use the request URI of the context to filter the routes via the route template.
Edit: After your comments I realized the routing configuration isn't what you were after.
If the end goal is to implement logging within your controllers, you may want to take a look at Tracing in ASP.NET Web API as there is support for tracing built-in to the Web API infrastructure.

Categories