ASP.NET Framework Web API
Installation
The following instructions are for ASP.NET Framework Web API. For instructions for how to install Raygun for ASP.NET Core Web API, see the ASP.NET documentation.
Step 1 - Install the NuGet package
Install the Mindscape.Raygun4Net.WebApi NuGet package into your project. You can either use the below dotnet CLI command, or the NuGet management GUI in the IDE you use.
dotnet add package Mindscape.Raygun4Net.WebApi
NuGet documentation for the Mindscape.Raygun4Net.WebApi package can be found here.
Step 2 - Setup Raygun in Web.config
In your Web.config file, find or add a <configSections>
element, which should be nested under the <configuration>
element, and add the following entry:
<section name="RaygunSettings" type="Mindscape.Raygun4Net.RaygunSettings, Mindscape.Raygun4Net"/>
Then reference it by adding the following line somewhere after the configSections
tag. Your app API key is displayed when you create a new application in your Raygun account, or can be viewed in the application settings. RaygunSettings
has many options which can be found here.
<RaygunSettings apikey="paste_your_api_key_here" />
Step 3 - Attach the RaygunWebApiClient
In your WebApiConfig
class (typically in the App_Start
directory), call the static RaygunWebApiClient.Attach(config)
method from within the Register
method:
using Mindscape.Raygun4Net.WebApi;
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
RaygunWebApiClient.Attach(config);
// Web API routes here
}
}
If you haven't already, make sure to register the WebApiConfig
class in the Application_Start
method in your Global.asax.cs
file:
protected void Application_Start()
{
GlobalConfiguration.Configure(WebApiConfig.Register);
}
The above set up will cause all unhandled exceptions to be sent to your Raygun account where you can easily view all of your error monitoring and crash report data.
Step 4 - TLS Configuration
Raygun's ingestion nodes require TLS 1.2.
If you are using Mindscape.Raygun4Net.WebApi < 6.0.3 and are using .NET 4.5 or earlier, you may need to enable these protocols in your application.
This is done by updating the protocol property in the Application_Start
method in your Global.asax.cs
file:
protected void Application_Start()
{
// Enable TLS 1.2
ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12 ;
}
Step 5 - Release
Deploy Raygun into your production environment for best results, or raise a test exception. Once we detect your first error event, the Raygun app will automatically update.
Manually sending exceptions
The above instructions will setup Raygun4Net to automatically detect and send all unhandled exceptions. Sometimes you may want to send exceptions manually - such as handled exceptions from within a try/catch block.
To manually send exceptions, create an instance of the RaygunWebApiClient class. The default constructor will use the API Key that you set up in Web.config. Alternatively, you could use the constructor that takes an API Key if you need to send the exception to a different one of your Raygun applications, or if you didn't set it in the config.
With the RaygunWebApiClient, you can call either the Send or SendInBackground methods. It's important to note that SendInBackground should only be used for handled exceptions, rather than exceptions that will cause the application to crash - otherwise the application will most likely shutdown all threads before Raygun is able to finish sending. Both the Send and SendInBackground methods have many overloads for sending additional data which are explained in the various feature sections below.
To include the HTTP request details, pass in the current request message to the client's SetCurrentHTTPRequest method when manually sending exceptions.
Here's an example of manually sending exceptions from a try/catch block:
try
{
// Do something here that might go wrong
}
catch (Exception e)
{
var client = new RaygunWebApiClient();
client.SetCurrentHttpRequest(ActionContext.Request);
client.SendInBackground(e);
}
Throw exceptions to avoid missing stack traces
Sometimes you may have code that detects that something has gone wrong, but doesn't actually throw an exception. If you want to log this to Raygun, it is tempting to just create a new exception instance and pass it through one of the RaygunWebApiClient send methods. Note however that a .NET exception needs to be thrown in order for its stack trace to be populated. So whenever you want to send a new exception instance to Raygun, make sure you are throwing the exception, then catch and send it from within a try/catch block as in the code example above. This will ensure that you log the stack trace which is useful for you to debug, and is used by Raygun to group exceptions.
Providing a custom RaygunWebApiClient to the automatic exception handlers
The Attach method mentioned in step 3 of the instructions above will use its own RaygunWebApiClient instance to send exceptions. If you need to use any of the features that require setting options on a RaygunWebApiClient instance, then you can provide the Attach method with your own RaygunWebApiClient as follows.
Use the static RaygunWebApiClient.Attach method overload that takes a function. Within this function, return a new (or previously created) RaygunWebApiClient instance. In this function you can set any additional options on the RaygunWebApiClient instance that you need - more information about each feature is described in the various sections below. Using the default constructor will pick up the api key you set in Web.config, or you can pass an api key into the constructor if you need to.
public static class WebApiConfig
{
private static RaygunWebApiClient _raygunClient;
public static void Register(HttpConfiguration config)
{
RaygunWebApiClient.Attach(config, () => {
if (_raygunClient == null) {
_raygunClient = new RaygunWebApiClient();
// Set any options on the RaygunWebApiClient instance here
}
return _raygunClient;
});
// Web API routes here
}
}
Modify or cancel messages
On a RaygunWebApiClient instance, attach an event handler to the SendingMessage event. This event handler will be called just before the RaygunWebApiClient sends an exception report - either automatically or manually. The event arguments provide the RaygunMessage object that is about to be sent. There are two different uses for this event handler:
- Modify the message. You can make any changes you want to the RaygunMessage object such as removing, adding or changing values. Any changes that you make will affect the exception report that gets sent to Raygun.
- Cancel the message. Sometimes you may get exceptions from parts of the application that you have no control over (such as 3rd party plugins) or due to issues that cannot be solved (such as various bot attacks). In this event handler, you can look through the properties of the RaygunMessage to determine if the exception is one that you don't care about. If so, you can then set e.Cancel = true to prevent Raygun4Net from sending it.
Here is an example of cancelling a message. Notice that this code uses the technique described above of passing a client instance to the Attach method.
public static class WebApiConfig
{
private static RaygunWebApiClient _raygunClient;
public static void Register(HttpConfiguration config)
{
RaygunWebApiClient.Attach(config, () => {
if (_raygunClient == null) {
_raygunClient = new RaygunWebApiClient();
_raygunClient.SendingMessage += (sender, args) =>
{
// This is an example of cancelling a message:
if ("BadServer".Equals(args.Message.Details.MachineName))
{
args.Cancel = true;
}
};
}
return _raygunClient;
});
// Web API routes here
}
}
Note that if an exception occurs within your SendingMessage event handler, Raygun4Net will detect this and send the new exception as well as the original exception that was being processed. When processing the new exception, the event handler will not be called again in order to avoid an infinite loop.
Custom grouping
When exception reports are sent to Raygun, they get grouped using our classification logic. We improve this logic every now and then, but sometimes you may come across scenarios where exceptions reports are grouped together or put into separate groups where you were not expecting. This can be from cases we are not yet handling, scenarios that are specific to your application, or unique grouping preferences you have. Raygun4Net lets you provide your own custom grouping logic before exceptions are sent to Raygun.
To use the custom grouping key feature, start by getting the RaygunWebApiClient instance used to send your exception reports and attach an event handler to the CustomGroupingKey event. This event gets fired before the SendingMessage event described in the section above. The event arguments provide both the original Exception object and the RaygunMessage object that is about to be sent. In the event handler, you can use whatever logic you want to build a grouping key (string) for the given exception. When the key is ready, set it to the CustomGroupingKey property of the event arguments. Exceptions that end up with the same key will be grouped together. Grouping keys have a limit of 100 characters.
Unless you have extreme grouping logic that needs to be applied to all exceptions, we recommend that you only apply custom grouping logic to scenarios that we are not handling for you. You can include checks in your event handler for certain types of exceptions for example, and only create a custom grouping key for them. Exceptions that you don't provide a custom grouping key for will be grouped in Raygun using the grouping classifiers we provide.
Here is an example of providing a custom grouping key. Notice that this code uses the technique described above of passing a client instance to the Attach method.
public static class WebApiConfig
{
private static RaygunWebApiClient _raygunClient;
public static void Register(HttpConfiguration config)
{
RaygunWebApiClient.Attach(config, () => {
if (_raygunClient == null) {
_raygunClient = new RaygunWebApiClient();
_raygunClient.CustomGroupingKey += (sender, args) =>
{
// This example simply performs pure message based grouping on basic Exception instances:
if (args.Message.Details.Error.ClassName.Equals("Exception"))
{
string key = args.Exception.Message;
args.CustomGroupingKey = key;
}
};
}
return _raygunClient;
});
// Web API routes here
}
}
Note that if an exception occurs within your CustomGroupingKey event handler, Raygun4Net will detect this and send the new exception as well as the original exception that was being processed. When processing the new exception, the event handler will not be called again in order to avoid an infinite loop.
Exclude errors by HTTP status code
If using the HTTP module, then you can exclude errors by their HTTP status code by providing a comma separated list of status codes to ignore in the configuration. For example if you wanted to exclude errors that return the I'm a teapot response code, you could use this configuration:
<RaygunSettings apikey="paste_your_api_key_here" excludeHttpStatusCodes="418" />
Exclude errors that originate from a local origin
To prevent Raygun4Net from sending exceptions that originate from a local origin (your debug/development machine), set the excludeErrorsFromLocal attribute to true as seen in the code below. This is useful if you find that everyone in your team sending exceptions from their local machines is noisy and pointless. This option is a convenient alternative to using Web.config transforms to do the same thing.
<RaygunSettings apikey="paste_your_api_key_here" excludeErrorsFromLocal="true" />
Remove sensitive request data
By default, Raygun4Net will send all form-fields and headers in the current HTTP request. If you have sensitive data in an HTTP request that you wish to prevent being transmitted to Raygun, you can provide a list of possible named values to remove:
<RaygunSettings apikey="paste_your_api_key_here" ignoreFormFieldNames="password,creditcard,cv2" />
Two attributes are available, to remove values from these two properties:
- ignoreFormFieldNames (ignores values from HttpRequestMessage.Form)
- ignoreHeaderNames (ignores values from HttpRequestMessage.Headers)
Or specify them in code with the following multi-parameter method:
_raygunClient.IgnoreFormFieldNames("password", "creditcard", "cv2");
Setting any of these options to *
will cause Raygun4Net to ignore all values in that category, so none of them are sent to Raygun. Also, by placing *
before, after or at both ends of a name, Raygun4Net will use that as an ends-with, starts-with or contains condition respectively when determining what to ignore.
Unique user tracking
Providing user information will allow your Raygun dashboard to display the number of unique users that each error or crash has affected. This is a huge help with prioritizing issues to solve that have the largest impact. You can provide whatever user information that will help you solve issues, but make sure to abide by any privacy policies that your company follows. At the very least, providing a unique guid will allow you to see the number of users that are affected by each error. If available, you could provide an ID that is meaningful to you such as a database ID. This could help you to look up information at your end that aids in solving issues. If you are able to provide a name and contact details, you'd be able to contact customers to let them know that issues they've encountered are being worked on, or have been solved.
There are a couple of ways to provide user information, the simplest of which is to set the User property of the RaygunWebApiClient instance to an identifier of your choosing:
_raygunClient.User = "user@email.com";
If a single identifier string isn't enough, you can set the UserInfo property instead to provide more information:
_raygunClient.UserInfo = new RaygunIdentifierMessage("user@email.com")
{
IsAnonymous = false,
FullName = "Robbie Robot",
FirstName = "Robbie"
};
Here are all the available RaygunIdentifierMessage properties:
- Identifier (passed into the constructor) is the unique identifier from your system for this user.
- IsAnonymous is a flag indicating whether the user is logged in (or identifiable) or if they are anonymous. An anonymous user can still have a unique identifier.
- Email The user's email address. If you use email addresses to identify your users, feel free to set the identifier to their email and leave this blank. We will use the identifier as the email address if it looks like one, and if no email address is specified in this field.
- FullName The user's full name.
- FirstName The user's first (or preferred) name.
- UUID A device identifier. Could be used to identify users across devices, or machines that are breaking for many users.
The string properties on a User have a maximum length of 255 characters. Users who have fields that exceed this amount will not be processed.
Tags
An overload of Send and SendInBackground allows you to include a list of tags with each manually sent exception:
_raygunClient.Send(exception, new List<string>() { "tag1", "tag2" });
Exceptions can be searched in your Raygun dashboard by tags that you've included.
Custom data
You can include key-value custom data using an overload of the Send or SendInBackground method. Values can be primitive types or rich object structures. All properties of objects and their children will be sent to Raygun. Cyclic object references will be detected and handled as appropriate, and any property getter that produces an exception will cause that property value to be displayed as the exception message.
_raygunClient.Send(exception, null, new Dictionary<string, object>() { { "key", "value" } });
The second parameter is the list of tags (mentioned above) which can be null if you don't have tags for the current exception.
Version numbering
By default, Raygun4Net will attempt to send the assembly version of your project with each report. If this is unavailable, or if you need to provide your own custom version value, you can do so by setting the ApplicationVersion property of the RaygunWebApiClient.
_raygunClient.ApplicationVersion = "1.3.37.0";
Alternatively, you can set the applicationVersion in Web.config as follows. If both are set, the property mentioned above takes precedence over the Web.config setting.
<RaygunSettings apikey="paste_your_api_key_here" applicationVersion="1.3.37.0" />
Stripping wrapper exceptions
If you have common outer exceptions that wrap a valuable inner exception which you'd prefer to group by, you can specify these by using the following multi-parameter method:
_raygunClient.AddWrapperExceptions(typeof(MyWrapperException));
The above example will cause MyWrapperException instances to be stripped away and never sent to Raygun. Instead, only the inner exception of any stripped exceptions will be sent. By default TargetInvocationException will always be stripped - see below to override this behavior.
AggregateException support (Only applicable to .NET 4.0 and higher)
AggregateException is a special case as they can hold multiple inner exceptions. By stripping AggregateException instances using the method described above, all inner exceptions will be sent to Raygun as separate exception reports. That way, each inner exception can be put into the appropriate individual groups and managed separately.
Prevent wrapper exception stripping
If you want to prevent Raygun4Net from stripping the default wrapper exception (TargetInvocationException) then you can call the multi-parameter RemoveWrapperExceptions method as shown below. This can also be useful if you've used the above instructions to cause Raygun4Net to strip a wrapper exception type that you later don't want to strip within a single execution of the app.
_raygunClient.RemoveWrapperExceptions(typeof(TargetInvocationException));
Proxy settings
The Raygun4Net provider uses the default Windows proxy settings or Web.config when sending messages to Raygun. If your proxy requires authentication credentials, you can provide these by setting the ProxyCredentials property of your RaygunWebApiClient instance:
_raygunClient.ProxyCredentials = new NetworkCredential("user", "password");
Disable the automatic capturing of request body content
The Raygun client will attempt to retrieve the content of requests that resulted in an exception. This feature can be disabled through the RaygunSettings
instance.
RaygunSettings.Settings.IsRawDataIgnored = true;
The provider is open source and available at the Raygun4Net repository.