Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions examples/aspnetcore8-mvc/.dockerignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
**/.classpath
**/.dockerignore
**/.env
**/.git
**/.gitignore
**/.project
**/.settings
**/.toolstarget
**/.vs
**/.vscode
**/*.*proj.user
**/*.dbmdl
**/*.jfm
**/azds.yaml
**/bin
**/charts
**/docker-compose*
**/Dockerfile*
**/node_modules
**/npm-debug.log
**/obj
**/secrets.dev.yaml
**/values.dev.yaml
LICENSE
README.md
!**/.gitignore
!.git/HEAD
!.git/config
!.git/packed-refs
!.git/refs/heads/**
85 changes: 85 additions & 0 deletions examples/aspnetcore8-mvc/Controllers/HomeController.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
using System.Diagnostics;
using aspnetcore8_mvc.Models;
using Microsoft.AspNetCore.Mvc;

namespace aspnetcore8_mvc.Controllers
{
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;

// The Bugsnag client (initialized in Program.cs) will be injected into your classes where you declare the IClient dependency.
// This allows you to report handled exceptions within your controller.
private readonly Bugsnag.IClient _bugsnag;

public HomeController(ILogger<HomeController> logger, Bugsnag.IClient bugsnag)
{
_logger = logger;
_bugsnag = bugsnag;
var request = HttpContext?.Request;

// A BeforeNotify callback lets you evaluate, modify, add and remove data before sending the error to bugsnag. The actions here will be applied to *all* errors, handled and unhandled.
_bugsnag.BeforeNotify(report =>
{
// In order to correlate errors with customer reports, or to see a list of users who experienced each error, you can attach user data in your callback
report.Event.User = new Bugsnag.Payload.User
{
Id = "006",
Name = "Hedy Lamarr",
Email = "[email protected]"
};

// This example makes some modifications that only apply to reports of error class "System.NotImplementedException".
if (report.OriginalException is NotImplementedException)
{
report.Event.Context = "an-important-context";
}

// note that calling report.Ignore() will discard the error report.
});
}

public IActionResult Index()
{
return View();
}

public IActionResult Contact()
{
// Report a handled exception
try
{
throw new Exception("Handled exception");
}
catch (Exception ex)
{
_bugsnag.Notify(ex, report =>
{
// You can also customise individual error reports before sending to Bugsnag.
report.Event.Metadata.Add("Don't worry", "I handled it");
});
}

return View();
}

public IActionResult Problems()
{
// You can leave manual breadcrumbs via the Breadcrumbs property on the client object
_bugsnag.Breadcrumbs.Leave("Here comes the exception...");

// You can optionally attach a type and metadata to a breadcrumb.
var metadata = new Dictionary<string, string> { { "message", "wait for it......" } };
_bugsnag.Breadcrumbs.Leave("Here comes the exception...", Bugsnag.BreadcrumbType.Navigation, metadata);

// Unhandled exceptions will be reported automatically
throw new NotImplementedException("We have a problem");
}

[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
}
}
32 changes: 32 additions & 0 deletions examples/aspnetcore8-mvc/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
# See https://aka.ms/customizecontainer to learn how to customize your debug container and how Visual Studio uses this Dockerfile to build your images for faster debugging.

# Depending on the operating system of the host machines(s) that will build or run the containers, the image specified in the FROM statement may need to be changed.
# For more information, please see https://aka.ms/containercompat

# This stage is used when running from VS in fast mode (Default for Debug configuration)
FROM mcr.microsoft.com/dotnet/aspnet:8.0-nanoserver-1809 AS base
WORKDIR /app
EXPOSE 8080
EXPOSE 8081


# This stage is used to build the service project
FROM mcr.microsoft.com/dotnet/sdk:8.0-nanoserver-1809 AS build
ARG BUILD_CONFIGURATION=Release
WORKDIR /src
COPY ["aspnetcore8-mvc.csproj", "."]
RUN dotnet restore "./aspnetcore8-mvc.csproj"
COPY . .
WORKDIR "/src/."
RUN dotnet build "./aspnetcore8-mvc.csproj" -c %BUILD_CONFIGURATION% -o /app/build

# This stage is used to publish the service project to be copied to the final stage
FROM build AS publish
ARG BUILD_CONFIGURATION=Release
RUN dotnet publish "./aspnetcore8-mvc.csproj" -c %BUILD_CONFIGURATION% -o /app/publish /p:UseAppHost=false

# This stage is used in production or when running from VS in regular mode (Default when not using the Debug configuration)
FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "aspnetcore8-mvc.dll"]
9 changes: 9 additions & 0 deletions examples/aspnetcore8-mvc/Models/ErrorViewModel.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
namespace aspnetcore8_mvc.Models
{
public class ErrorViewModel
{
public string? RequestId { get; set; }

public bool ShowRequestId => !string.IsNullOrEmpty(RequestId);
}
}
74 changes: 74 additions & 0 deletions examples/aspnetcore8-mvc/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
using Bugsnag.AspNet.Core;

var builder = WebApplication.CreateBuilder(args);

// Initialize Bugsnag to begin tracking errors. Only an api key is required, but here are some other helpful configuration details:
builder.Services.AddBugsnag(configuration =>
{
// Replace this with your own API key.
configuration.ApiKey = "YOUR_API_KEY";

// We mark stacktrace lines as inProject if they come from namespaces included in your project namespaces.
configuration.ProjectNamespaces = new[] { "aspnetcore8_mvc" };

// Project roots are used to strip file paths in each error reports stack trace in order to normalize them across builds.
// configuration.ProjectRoots = new[]{ @"/Users/bgates/bugsnag-dotnet/examples/" };
configuration.AppType = "worker";
configuration.AppVersion = "2.5.1";

// Bugsnag can track the number of “sessions” that happen in your application, and calculate a crash rate for each release. This defaults to false.
configuration.AutoCaptureSessions = true;

// Metadata that will be attached to all error reports sent by the client.
configuration.GlobalMetadata = new[] { new KeyValuePair<string, object>("company", new Dictionary<string, string> {
{ "department", "Westworld" },
{ "name", "Delos Destinations, Inc." },
// these values will be redacted from the report due to the MetadataFilters configuration.
{ "password", "frqhopsys76659" },
{ "creditcard", "1234-5678-1234-5678" }
})
};

// Use MetadataFilters to remove sensitive data such as passwords, and credit card numbers from error reports.
// Any matching keys in the metadata of the report will have their values replaces with [FILTERED]. "password" and "Authorization" are filtered by default.
configuration.MetadataFilters = new[] { "password", "creditcard" };

// Use NotifyReleaseStages to disable error reporting in certain environments, e.g. ignore development errors.
configuration.NotifyReleaseStages = new[] { "staging", "production" };
configuration.ReleaseStage = "staging";

// Use IgnoreClasses to define exception types that should not be reported.
// configuration.IgnoreClasses = new [] { typeof(Bugsnag.NotThatBadException) };
});

builder.Services.AddControllersWithViews();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();

// Bugsnag automatically reports exceptions that the exception handler middleware catches.
app.UseExceptionHandler("/Home/Error");
}
else
{
// Bugsnag automatically reports exceptions that the developer exception page middleware catches.
app.UseDeveloperExceptionPage();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");

app.Run();
44 changes: 44 additions & 0 deletions examples/aspnetcore8-mvc/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
# .NET 8 ASP.NET Core (MVC) Example Application

This example shows how you can use the BugSnag .NET notifier in a basic ASP.NET Core MVC app.

Try this out with [your own BugSnag account](https://app.bugsnag.com/user/new) by replacing the placeholder API key with your own. You'll be able to see how the errors are reported in the dashboard, how breadcrumbs are left, how errors are grouped and how they relate to the original source.

## Requirements

- Visual Studio 2022
- .NET 8.0 SDK

## Setup

The example project is set up to use Bugsnag packages built locally from source. Or, alternatively, you can use Visual Studio to install the latest version from `nuget.org`.

1. Clone the repo and run the build script from the repository root to build and generate the local packages:
```sh
git clone https://github.com/bugsnag/bugsnag-dotnet.git
cd bugsnag-dotnet
.\build.ps1 --Target Pack
```

1. `cd` into this directory:
```sh
cd examples/aspnetcore8-mvc
```

1. In the [Program.cs](Program.cs) file Replace the `API_KEY` placeholder with your own Bugsnag API key.

1. In the [aspnetcore8-mvc.csproj](aspnetcore8-mvc.csproj) file, make sure `Bugsnag.AspNet.Core` is included in your NuGet packages.

1. To report non-fatal exceptions, in the [HomeController.cs](Controllers/HomeController.cs) file, make sure to declare the `IClient` dependency where you want the Bugsnag client injected into your classes.

1. Build the application:
```sh
dotnet build
```

1. Run the application:
```sh
dotnet run
```

1. View the example page which will (most likely) be served at: http://localhost:5000
12 changes: 12 additions & 0 deletions examples/aspnetcore8-mvc/Views/Home/Contact.cshtml
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
@{
ViewData["Title"] = "Contact";
}

<h3>BugSnag</h3>
<p>Focused and powerful error monitoring for web, mobile, and server apps.</p>

<p><a href="https://bugsnag.com">www.bugsnag.com</a></p>

<address>
<strong>Support:</strong> <a href="mailto:[email protected]">[email protected]</a><br />
</address>
18 changes: 18 additions & 0 deletions examples/aspnetcore8-mvc/Views/Home/Index.cshtml
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
@{
ViewData["Title"] = "Home Page";
}


<div class="row">
<div class="col-md-7 ">
<h2>BugSnag ASP.NET Core Example</h2>
<p>Use the navigation bar above to send errors to your dashboard.</p>
<ul>
<li>Contact - will trigger a handled exception</li>
<li>Problems - will trigger an unhandled exception</li>
</ul>

<p>visit <a href="https://app.bugsnag.com">app.bugsnag.com</a> to see the results!</p>
</div>

</div>
7 changes: 7 additions & 0 deletions examples/aspnetcore8-mvc/Views/Home/Problems.cshtml
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
@{
ViewData["Title"] = "There be errors here!";
}
<h2>@ViewData["Title"]</h2>
<h3>@ViewData["Message"]</h3>

<p>Use this area to provide additional information.</p>
25 changes: 25 additions & 0 deletions examples/aspnetcore8-mvc/Views/Shared/Error.cshtml
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
@model ErrorViewModel
@{
ViewData["Title"] = "Error";
}

<h1 class="text-danger">Error.</h1>
<h2 class="text-danger">An error occurred while processing your request.</h2>

@if (Model.ShowRequestId)
{
<p>
<strong>Request ID:</strong> <code>@Model.RequestId</code>
</p>
}

<h3>Development Mode</h3>
<p>
Swapping to <strong>Development</strong> environment will display more detailed information about the error that occurred.
</p>
<p>
<strong>The Development environment shouldn't be enabled for deployed applications.</strong>
It can result in displaying sensitive information from exceptions to end users.
For local debugging, enable the <strong>Development</strong> environment by setting the <strong>ASPNETCORE_ENVIRONMENT</strong> environment variable to <strong>Development</strong>
and restarting the app.
</p>
Loading