What is causing the error that swagger is already in the route collection for Web API 2? - asp.net-web-api2

I installed Swagger in my ASP.Net MVC Core project and it is documenting my API beautifully.
My co-worker asked me to install it in a full framework 4.6.1 project so I've done the following.
In Package Console Manager run:
Install-Package Swashbuckle
To get your Test Web API controller working:
1) Comment this out in the WebApi.config:
// config.SuppressDefaultHostAuthentication();
// config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
Now this URL:
http://localhost:33515/api/Test
brings back XML:
<ArrayOfstring xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
<string>value1</string>
<string>value2</string>
</ArrayOfstring>
In Global.asax Register() I call:
SwaggerConfig.Register();
In AppStart.Swagger.Config Register() I put:
public class SwaggerConfig
{
public static void Register()
{
var thisAssembly = typeof(SwaggerConfig).Assembly;
GlobalConfiguration.Configuration
.EnableSwagger(c =>
{
c.SingleApiVersion("v1.0", "HRSA CHAFS");
c.IncludeXmlComments(GetXmlCommentsPath());
})
.EnableSwaggerUi(c =>
{});
}
private static string GetXmlCommentsPath()
{
var path = String.Format(#"{0}bin\Services.XML", AppDomain.CurrentDomain.BaseDirectory);
return path;
}
}
Now I get this error:
"A route named 'swagger_docsswagger/docs/{apiVersion}' is already in the route collection. Route names must be unique."
I've been stuck on this for hours.
How do you get rid of this?

This can happen when you re-name your .NET assembly. A DLL with the previous assembly name will be present in your bin folder. This causes the swagger error.
Delete your bin folder and re-build your solution.
This resolves the swagger error.

Swagger config uses pre-application start hook, so you don't need to call SwaggerConfig.Register() explicitly. Otherwise Register method is called twice.
[assembly: PreApplicationStartMethod(typeof(SwaggerConfig), "Register")]

in my case i added another project as refrence and that other project has swagger too.
i remove that refrence and move needed code to new project.

I solved the problem by deleting the SwaggerConfig.cs file from the App_Start folder as I had already created it manually.
Take a look at this link, here also has more useful information:
A route named 'DefaultApi' is already in the route collection error

In my experience the error occurs when you add reference to another project and that project is a service and it occurs on the SwaggerConfig of the referenced project. Removing project reference usually solve the problem, if you need to share classes I suggest you to create a specific project as Class Library and add its reference to both your services

Related

Telerik Reporting .NET 5 walkthrough yields error "ConfigurationHelper does not exist in current context"

Following the 'How to Host Reports Service in ASP.NET Core in .NET 5' walk through here and early on they have you paste the following in ConfigureSerivces:
// Configure dependencies for ReportsController.
services.TryAddSingleton<IReportServiceConfiguration>(sp =>
new ReportServiceConfiguration
{
ReportingEngineConfiguration = ConfigurationHelper.ResolveConfiguration(sp.GetService<IWebHostEnvironment>()),
HostAppId = "Net5RestServiceWithCors",
Storage = new FileStorage(),
ReportSourceResolver = new UriReportSourceResolver(
System.IO.Path.Combine(sp.GetService<IWebHostEnvironment>().ContentRootPath, "Reports"))
});
However ConfigurationHelper is flagged as 'does not exist in current context'.
I know I probably need to reference an assembly but I did add all the supposed required dependencies via nuget Telerik.Reporting.Services.AspNetCore.Trial.
So I don't know what assembly I need to get ConfigurationHelper.
I suspect this is a really stupid question because there is virtually nothing on the internet about ConfigurationHelper which means the answer is so simple people don't even need to google it.
So what do I need to add to a brand new ASP.NET Core Web Application 5.0 with nuget Telerik.Reporting.Services.AspNetCore.Trial in order to resolve ConfigurationHelper?
ConfigurationHelper is just a static class in your project, you can rename it if you want, then use it in this line ReportingEngineConfiguration = ConfigurationHelper.ResolveConfiguration(sp.GetService<IWebHostEnvironment>()),
Taken from the article you have posted:
static class ConfigurationHelper
{
public static IConfiguration ResolveConfiguration(IWebHostEnvironment environment)
{
var reportingConfigFileName = System.IO.Path.Combine(environment.ContentRootPath, "appsettings.json");
return new ConfigurationBuilder()
.AddJsonFile(reportingConfigFileName, true)
.Build();
}
}
You can have a look at the demo projects in your installation, the path should be similar to C:\Program Files (x86)\Progress\Telerik Reporting R2 2022\Examples\CSharp.NET 5\ReportingRestServiceCorsDemo

What does compilationOptions.emitEntryPoint mean?

Just installed the rc1 tools and created a new web project to see what has changed in the template.
I noticed that project.json now contains:
"compilationOptions": {
"emitEntryPoint": true
}
But it's unclear what this does.
Does anyone have an idea?
As mentioned below: It looks like it is a flag to the compiler to indicate that the project is a console application vs. a library (namely: a console application must contain public static void Main())
You can see from the source here.
In the new RC1 default web application template, you'll notice at the bottom of Startup.cs there is a new expression bodied method that acts as the entry point:
public static void Main(string[] args) => WebApplication.Run<Startup>(args);
If you remove this method then perform a build (dnu build) you will get an error:
error CS5001: Program does not contain a static 'Main' method suitable for an entry point
However, if you change the emitEntryPoint flag to false and attempt to build again, it will succeed. This is because it is creating a library instead of a console app.
I see this in the source;
var outputKind = compilerOptions.EmitEntryPoint.GetValueOrDefault() ?
OutputKind.ConsoleApplication : OutputKind.DynamicallyLinkedLibrary;
Looks like it tells the compiler whether to create a Console Application or a Library.
Additionaly, if you create a new Class Library (Package) and Console Application (Package) in VS2015 you'll see that project.json for the Console Application includes the following, while the Class Library does not;
"compilationOptions": {
"emitEntryPoint": true
}

Use of AuthConfig, BundleConfig, FilterConfig , RouteConfig and WebApiConfig in App_Start() folder in MVC

Can you please explain in detail, the use of App_Start() folder in MVC4?
I see that this folder is actually not available in previous versions of MVC.
There are 5 files in this folder.
AuthConfig
BundleConfig,
FilterConfig,
RouteConfig,
WebApiConfig.
App_Start is just another folder that groups together ASP.NET MVC configuration, which in previous versions of ASP.NET MVC was done in Global.asax.
ASP.NET MVC introduces more and more configuration elements, and this folder is ideal to place this configuration. For example, MVC 5's new auth. configuration, such as for third-party login providers, are also placed within this folder (in Startup.Auth.cs).
App_Start is not a ASP.NET special folder recognized by ASP.NET/IIS. You can rename the folder if you want. The name is just a convention, like App_GlobalResouces etc.
Update:
Below are some information and reference points for each file. The use of these files are pretty straightforward. I have included few online references that might help your to understand more.
AuthConfig — registers external authentication providers.
See ASP.NET MVC external authentication providers for more information.
BundleConfig — registers your CSS and JS so they can be bundled and minified. See also ASP.NET MVC: Guidance: Bundling and Minification.
WebApiConfig — only applicable if you are using Web API. It can be used to configure Web API-specific routes, any Web API settings and Web API services. See also configuring ASP.NET MVC Web API 2
FilterConfig — registered global filters. These filters are applied to all actions and controllers. See also ASP.NET MVC 3: Global action filters
RouteConfig — you already found information.
App_start folder has been introduced in Mvc4. It contains various configurations files like:
BundleConnfig.cs
FilterConfig.cs
RouteConfig.cs
WebApiConfig.cs
AuthConfig.cs
App_start is not a special folder in MVC nor the class files inside this, these are just normal class files with different application
configurations(filtering, bundling, routing etc.) and all these settings gets registered within Application_Start method of Global.asax.cs file.
BundleConfig.cs:
This is used to create and register bundles for CSS and JS files. for
eg. jQuery,jQueryUI,jQuery validation,Modernizr and Site CSS..
Bundling and minification are two techniques to improve request load time by
reducing the number of requests to the server and reducing the size of
requested assets (such as CSS and JavaScript.)
Microsoft provides assembly Microsoft.Web.Optimization for the same
for eg.
Lets create two Bundles. one for style(css) and another for script(javascript)
You can create bundle for css and javascripts respectively by calling
BundleCollection class Add() method within BundleConfig.cs file.
STEP 1:
Creating Style Bundle
bundles.Add(new StyleBundle("~/Content/css").Include("~/Content/site.min.css",
"~/Content/mystyle.min.css"));
Creating Script Bundle
bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
"~/Scripts/jquery-1.7.1.min.js",
"~/Scripts/jquery.validate.min.js"));
STEP 2:
Above bundles are defined in BundleConfig class as:
public class BundleConfig
{
public static void RegisterBundles(BundleCollection bundles)
{
//Adding StyleBundle to BundleCollection
bundles.Add(new StyleBundle("~/Content/css").Include("~/Content/site.min.css",
"~/Content/mystyle.min.css"));
//Adding ScriptBundle to BundleCollection
bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
"~/Scripts/jquery-1.7.1.min.js",
"~/Scripts/jquery.validate.min.js"));
}
}
STEP 3:
Registering Bundle
All bundles are registered in the Application_Start event of Global.asax:
protected void Application_Start()
{
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
Minification is a technique for removing unnecessary characters (like
white space, newline, tab) and comments from the JavaScript and CSS
files to reduce the size, in turn improve load time of a web page. for
eg. jquery-1.7.1.min.js is the minified js file for jquery-1.7.1,
mostly used for production environment, for non-prod you can better use non-
minified js to have better readability.
for eg.
A Jquery function in uncompressed js may look something like:
( function( global, factory ) {
"use strict";
if ( typeof module === "object" && typeof module.exports === "object" ) {
// For CommonJS and CommonJS-like environments where a proper `window`
// is present, execute the factory and get jQuery.
// For environments that do not have a `window` with a `document`
// (such as Node.js), expose a factory as module.exports.
// This accentuates the need for the creation of a real `window`.
// e.g. var jQuery = require("jquery")(window);
// See ticket #14549 for more info.
module.exports = global.document ?
factory( global, true ) :
function( w ) {
if ( !w.document ) {
throw new Error( "jQuery requires a window with a document" );
}
return factory( w );
};
} else {
factory( global );
}
same above function in compressed or minified js will look like:
!function(a,b){"use strict";"object"==typeof module&&"object"==typeof module.exports?module.exports=a.document?b(a,!0):function(a){if(!a.document)throw new Error("jQuery requires a window with a document");return b(a)}:b(a)}
FilterConfig.cs:
This is used to create and register global MVC filter:
for eg.
Authentication filters (Executed First)
Authorization filters
Action filters
Result filters
Exception filters (Executed Last)
Note: As mentioned above Filters are executed in an order.
for eg. Authentication Filters introduced with MVC5:
public interface IAuthenticationFilter
{
void OnAuthentication(AuthenticationContext filterContext);
void OnAuthenticationChallenge(AuthenticationChallengeContext filterContext);
}
You can create your CustomAuthentication filter attribute by implementing
IAuthenticationFilter as shown below-
public class CustomAuthenticationAttribute : ActionFilterAttribute, IAuthenticationFilter
{
public void OnAuthentication(AuthenticationContext filterContext)
{
//logic goes here
}
Runs after the OnAuthentication method
public void OnAuthenticationChallenge(AuthenticationChallengeContext
filterContext)
{
{
//logic goes here
}
}
Configuring Filters
You can configure your own custom filter into your application at
following three levels:
Global level
By registering your filter into Application_Start event of
Global.asax.cs file:
protected void Application_Start()
{
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
}
Controller level
By putting your filter on the top of the controller name:
[Authorize(Roles="Admin")]
public class AdminController : Controller
{
// Logic goes here
}
Action level
By putting your filter on the top of the action name:
public class UserController : Controller
{
[Authorize(Users="User1,User2")]
public ActionResult LinkLogin(string provider)
{
// Logic goes here
return View();
}
}
RouteConfig.cs:
This is used to register various route patterns for your Asp.Net MVC
application. Routing plays an important role in an ASP.NET MVC Application
execution flow, it maps request URL to a specific controller action using a
Routing Table. We can define Routing Rules for the engine, so that it can map > incoming URLs to appropriate controller. Routing Engine uses routing rules
that are defined in Global.asax file in order to parse the URL and find out
the path of corresponding controller. We can find the following piece of code > in Application_Start() method of Global.asax file.
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
We can find RouteConfig.cs file under App_Start folder. If we follow
this method in RouteConfig class, we will find one default configured
route as follows. Line 3 to 7 is configuring one default route.
public static void RegisterRoutes(RouteCollection routes)
{
1. routes.IgnoreRoute(“{resource}.axd/{*pathInfo}”);
2.
3. routes.MapRoute(
4. name: “Default”,
5. url: “{controller}/{action}/{id}”,
6. defaults: new { controller = “Home”, action = “Index”, id = UrlParameter.Optional }
7. );
}
Line 4 : Name for the route. Line 5 : represent URL : Controller,
action followed by id (if any). Line 6 : default controller will be
Home, default action will be Index and Id is optional.
WebApiConfig.cs:
This is used to register various WEB API routes like as Asp.Net MVC, as well as set any addtional WEB API configurations settings.
AuthConfig.cs:
Used to register external authentication providers
for eg. if you want to enable users to log in with credentials from an external provider, such as Facebook, Twitter, Microsoft, or Google, and then integrate some of the functionality from those providers into your web application.
App_start folder has been introduced in Mvc4. It contains various configurations files like as :
BundleConnfig.cs,
FilterConfig.cs,
RouteConfig.cs,
WebApiConfig.cs
for you application.All those settings are registered within App_Start method of Global.asax.cs file
BundleConfig.cs:
This is used to create and register bundles for CS and JS files.By default various bundles are added in this file including jQuery,jQueryUI,jQuery validation,Modernizer and Site Css..
FilterConfig.cs-
This is used to create and register global MVC filter error filter,action filter etc.By default it contains HandleErrorAttribute filter.
RouteConfig.cs-
This is used to register various route patterns for your Asp.Net MVC application. By default,one route is registered here named as Default Route.
WebApiConfig.cs-
This is used to register various WEB API routes like as Asp.Net MVC,as well as set any additional WEB API configurations settings.
In the previous versions of MVC, we just have RegisterRoutes() method in global.asax file to configure the routing. MVC 4 has built in templates to develop mobile web applications, web apis(restful http services).so to configure the routings for all those template driven development ,we will be using the
AuthConfig.cs(Authorization),BundleConfig.cs(web potimization),,FilterConfig.cs,RouteConfig.cs,WebApiConfig.cs(WEB API) files and they will be mainteained in App_start folder.
Lets have a look at each those config.cs files.
AuthConfig.cs - settings in this file allows you to login to ASP.NET MVC site using third party client credentials like fb account,google account,yahoo account etc..or you can register also.
BundleConfig.cs: settings in this file allows to improve the performance of an applications using bundling...
WebApiConfig: sets the routing settings for WEB API (Note:No action needed in url)
AuthConfi g.cs: Used to confi gure security settings, including sites for OAuth login.
BundleConfi g.cs: Used to register bundles used by the bundling and minifi cation
system. Several bundles are added by default, including jQuery, jQueryUI, jQuery
validation, Modernizr, and default CSS references.
FilterConfi g.cs: Unsurprisingly, this is used to register global MVC fi lters. The only
fi lter registered by default is the HandleErrorAttribute, but this is a great place to put
other fi lter registrations.
RouteConfi g.cs: Holds the granddaddy of the MVC confi g statements, Route confi
guration.
WebApiConfi g.cs: Used to register Web API routes, as well as set any additional Web
API confi guration settings.
All those settings are registered within the App_Start method of Global.asax.cs file
BundleConfig.cs:
This is used to create and register bundles for CS and JS files that we have in the template.
FilterConfig.cs-
This is used to create and register global MVC filter error filter
RouteConfig.cs-
This is used to register various route patterns for your Asp.Net MVC application.
WebApiConfig.cs-
This is used to register various WEB API routes like want login with credentials from an external provider, such as Facebook, Twitter, Microsoft, or Google,

signalR : /signalr/hubs is not generated

I can get this tutorial to work in a new project, but not in my existing project.
My project is an ASP.Net MVC 4 web application with the following attribute in the web.config file:
<appSettings>
<add key="webpages:Enabled" value="true"/>
</appSettings>
This is because my application is a Single-Page-Application, which uses AngularJS on the client side. The only page in my application is index.cshtml, to which I've added the relevant code for signalR:
<!-- signalR chat -->
<script src="~/Scripts/jquery.signalR-1.0.0.js"></script>
<!--Reference the autogenerated SignalR hub script. -->
<script src="/signalr/hubs"></script>
<!--Add script to update the page and send messages.-->
<script type="text/javascript">
$(function () {
// Declare a proxy to reference the hub.
var chat = $.connection.chatHub;
// Create a function that the hub can call to broadcast messages.
chat.client.broadcastMessage = function (name, message) {
// Html encode display name and message.
var encodedName = $('<div />').text(name).html();
var encodedMsg = $('<div />').text(message).html();
// Add the message to the page.
$('#discussion').append('<li><strong>' + encodedName
+ '</strong>: ' + encodedMsg + '</li>');
};
// Get the user name and store it to prepend to messages.
$('#displayname').val(prompt('Enter your name:', ''));
// Set initial focus to message input box.
$('#message').focus();
// Start the connection.
$.connection.hub.start().done(function () {
$('#sendmessage').click(function () {
// Call the Send method on the hub.
chat.server.send($('#displayname').val(), $('#message').val());
// Clear text box and reset focus for next comment.
$('#message').val('').focus();
});
});
});
</script>
Then I've got the ChatHub.cs file:
public class ChatHub : Hub
{
public void Send(string name, string message)
{
// Call the broadcastMessage method to update clients.
Clients.All.broadcastMessage(name, message);
}
}
And finally in the global.asax:
protected void Application_Start()
{
RouteTable.Routes.MapHubs();
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
When I run the application, the /signalr/hubs file is not generated. I get a 404 when requesting the file, and it crashes on the line:
chat.client.broadcastMessage = function (name, message) { ....
because chat is null as the previous line did not find chatHub:
var chat = $.connection.chatHub;
Does anyone know what's wrong with my code ?
UPDATE
I have solved my problem by changing the line::
<script src="/signalr/hubs"></script>
to
<script src="~/signalr/hubs"></script>
I have solved my problem by changing the line::
<script src="/signalr/hubs"></script>
to
<script src="~/signalr/hubs"></script>
Also, the reason why /signalr/hubs are not generated is forget to Map SignalR in OWIN Startup Configuration.
public class Startup
{
public void Configuration(IAppBuilder appBuilder){
...
appBuilder.MapSignalR();
...
}
...
In my case, it was because my ChatHub class was not marked public.
I had a similar problem where the hubs file wasn't being generated. It looks like the OP was following the steps here. The way I fixed the problem had to do with the jquery includes. The tutorial I linked below was written with jquery 1.6.4 and jquery-signalr version 2.1.0. When Visual Studio generated the Scripts folder for me, it used jquery version 1.10.2 and jquery-signalr version 2.0.2.
The way I fixed this was simply to edit the index.html file. Note that you can use Chrome's javascript console window Ctrl+Shift+J to see errors.
For me the solution was to reinstall all the packages and restore all the dependecies.
Open nuget powershell console and use this command.
Update-Package -Reinstall
I'll like to add that the signalR Readme file have some note about this issue.
And also if your signalR page is in a PartialView some script should be place in the master page.
Please see http://go.microsoft.com/fwlink/?LinkId=272764 for more information on using SignalR.
Upgrading from 1.x to 2.0
-------------------------
Please see http://go.microsoft.com/fwlink/?LinkId=320578 for more information on how to
upgrade your SignalR 1.x application to 2.0.
Mapping the Hubs connection
----------------------------
To enable SignalR in your application, create a class called Startup with the following:
using Microsoft.Owin;
using Owin;
using MyWebApplication;
namespace MyWebApplication
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
app.MapSignalR();
}
}
}
Getting Started
---------------
See http://www.asp.net/signalr/overview/getting-started for more information on how to get started.
Why does ~/signalr/hubs return 404 or Why do I get a JavaScript error: 'myhub is undefined'?
--------------------------------------------------------------------------------------------
This issue is generally due to a missing or invalid script reference to the auto-generated Hub JavaScript proxy at '~/signalr/hubs'.
Please make sure that the Hub route is registered before any other routes in your application.
In ASP.NET MVC 4 you can do the following:
<script src="~/signalr/hubs"></script>
If you're writing an ASP.NET MVC 3 application, make sure that you are using Url.Content for your script references:
<script src="#Url.Content("~/signalr/hubs")"></script>
If you're writing a regular ASP.NET application use ResolveClientUrl for your script references or register them via the ScriptManager
using a app root relative path (starting with a '~/'):
<script src='<%: ResolveClientUrl("~/signalr/hubs") %>'></script>
If the above still doesn't work, you may have an issue with routing and extensionless URLs. To fix this, ensure you have the latest
patches installed for IIS and ASP.NET.
In my case i was missing :
app.MapSignalR();
in public void Configuration(IAppBuilder app) function located in startup.cs
Some advice for those that start scaling out from the get go. In my case I was working on getting a remote client to work and never realized that
A. the tutorial example lists the web app(server) startup in a using statement, after which the web app disposes properly and no long exists.
I got rid of the using statement and keep a reference to the web app
for later disposal
B. the client has a different url than the server. the example relies on them having the same url. the "/signalr/hubs" is an endpoint run by the signalr server, called by the signalr client to get a script of all the hubs the server implements.
You need to include "http://myServerURL/signalr/hubs", rather than making it
relative to the client.
No lies. This tripped me up for a solid 2 weeks, because by some magic the solution worked anyways on my coworker's setup. This caused me to keep looking for IIS settings and firewall settings and CORS settings that must have been blocking the connection on my computer. I scavenged every last stack overflow question I could and the ultimate answer was that I should have just implemented a heartbeat monitor on the web app from the start.
Good luck and hopefully this saves other people some time.
See if Microsoft.Owin.Host.Systemweb nuget package is not installed, and therefore not building the dynamic js lib.
OwinStartup not firing

Migration from WCF WebApi to MVC4 Api - Registering global error handler

I am migrating a project that was developed using WebApi Preview 5 (when it was part of WCF) to the final release of WebApi (part of MVC4). There is a document describing the process but it is extremely simplistic and doesn't cover most of the issues.
Now one of the issues I am facing is that a GlobalErrorHandler was created by inheriting from HttpErrorHandler and then overriding OnTryProvideResponse and that was used to hook error handling with Elmah. Now that was registered on AppStart with a line like this:
var configuration = new WebApiConfiguration();
//some other configuration for security and CreateInstance
configuration.ErrorHandlers =
(handlers, endpoint, description) => handlers.Add(new GlobalErrorHandler())
};
//then some registration
RouteTable.Routes.MapServiceRoute<SomeObject>("routeName", configuration);
and then mapping different route to this configuration. All this code doesn't work in the new world of MVC4 WebApi, it seems like there is a conflict between HttpErrorHandler and it can't even implement its members properly.
Now I've seen general posts about how to register Elmah with WebApi but I am trying to stick to the original code as much as possible and I am assuming - may be I am wrong - that there is a direct equivalent to what Microsoft had in the Preview version and what they released in the final one. So my questions:
What is the equivalent of this Global Error handling registation in ASP.NET MVC4 WebApi?
Do I need to do the configuration the same way it is done here (default webapi samples project doesn't seem to have similar code)
What is the equivalent of that route registration line of code: RouteTable.Routes.MapServiceRoute("routeName", configuration);
If you create a quick one-off WebApi MVC project in Visual Studio you will see an App_Start folder which contains some classes which have static methods for handling the registration, specifically:
FilterConfig.cs
WebApiConfig.cs
WebApi Config is where you need to register routes etc...
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
Filter config is what you need to handle your global errors... Filter config has a default error handler attribute added which you can swap out or out
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
}
Global.asax calls these static registration scripts like so:
protected void Application_Start()
{
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
}
In regard to Elmah it appears simplying including the Nuget package will register it...
Look for the package Elmah.Mvc
PM> Install-Package Elmah.MVC
it used to be like this How to get ELMAH to work with ASP.NET MVC [HandleError] attribute? but now according to this blog it has changed:
HandleErrorAttribute inside If you tried to use ELMAH in ASP.NET MVC,
you are probably implemented your own HandleErrorAttribute, as it's
shown in this example. You no longer need to apply this custom code
with Elmah.MVC. As soon you installed package, so can safely remove
your HandleError attribute, since it's already included into package.
This now appears to register itself in the Web.Config as a managedHandler so your code does not need to reference Elmah directly.