Asp.Net Web Api Logging - asp.net-web-api

I want to setup logging on my asp.net web api (Not Asp.Net Core), and want to make sure that I follow best practices (as close as possible). I am using SeriLog in my services, and would like to use this product for my Web Api as well. I am not sure of the best way to setup logging in Web API, and I would like to set it up such that depending on the context (my api serves multiple apps) I would like to be able to log to a separate Microsoft Sql Server. Can somebody please provide some direction on how to get started at this task, potential pitfalls, or a link to an article that I have yet to find on how to set this up in Asp.Net?

You can create a centralized logger project and add serilog packages to this project only, and reference this project where you need to use serilog (your services).
And configure serilog using Serilog.Settings.AppSettings package so each service project will read its own configuration (Ex: separate Microsoft SQL Server) from <appSettings> section in service web.config useing the ReadFrom.AppSettings() extension method on your LoggerConfiguration
Sample Logger Class
public static class Logger
{
private static readonly ILogger _dbLogger;
static Logger()
{
_dbLogger = new LoggerConfiguration()
.ReadFrom.AppSettings()
.CreateLogger();
}
public static void Log(string error)
{
_dbLogger.Error(error);
}
}
Sample appSettings configuration
<add key="serilog:using:MSSqlServer" value="Serilog.Sinks.MSSqlServer" />
<add key="serilog:write-to:MSSqlServer.connectionString" value="Server=..."/>
<add key="serilog:write-to:MSSqlServer.tableName" value="Logs"/>
<add key="serilog:write-to:MSSqlServer.autoCreateSqlTable" value="true"/>

There is a library from Serilog (MSSQL-Server)

Related

Asp.Net Core Project Combine Web and Windows Service

Is it possible to have a service API that can handle API request / responses, but also have an internal service running on a timer. e.g Every 2 hours check database Logs and delete info logs, something like that?
Asp.Net Core is like any other .NET Core application, it has a Main function where you can start all non-blocking operations you want.
In Program.cs:
public static void Main(string[] args)
{
//Here you can start your timer (maybe using a dedicated class)
//Just avoid blocking code...
//Starting Asp.Net Core web host.
BuildWebHost(args).Run();
}
If you find more confortable, you can do the same inside Configure/ConfigureServices methods in your Startup.cs file, hopefully creating a specific service for your purpose.

Programatically configure sso settings using kentor

I have an MVC application (.Net Framework 4.5) which is been there for the last three years and using Forms Authentication mechanism. Now we want to integrate SSO feature with the help of Okta. Using KentorIT Authentication services I was able to integrate Okta with my mvc application. In that, all the configurations are being set in the web.config file (eg: entityId, signOnUrl etc.). Is there a way to programmatically configure these sso settings? I found that KentorAuthServicesSection is the class that we have to instantiate to do the process. Currently its reading the settings from configuration file.
public class KentorAuthServicesSection : ConfigurationSection
{
private static readonly KentorAuthServicesSection current =
(KentorAuthServicesSection)ConfigurationManager.GetSection("kentor.authServices");
}
So modifying this ConfigurationManager.GetSection("kentor.authServices") part with a custom implementation will do the job? or is there any other good approach ?
You can just use the options classes directly -- no need to customize the GetSection.
I'm assuming you are using the Mvc module. In which case you want to set the options on the AuthServicesController during application startup, e.g.
Kentor.AuthServices.Mvc.AuthServicesController.Options = myOptions;
With your own construction of these same configuration classes. For example:
var spOptions = new SPOptions
{
EntityId = new EntityId("http://localhost:57294/AuthServices"),
ReturnUrl = new Uri("http://localhost..."),
//...
};
options = new KentorAuthServicesAuthenticationOptions(false)
{
SPOptions = spOptions
};
The false in this constructor tells it not to read from the configuration system.
There is a larger example in the OWIN sample project:
https://github.com/KentorIT/authservices/blob/v0.21.1/SampleOwinApplication/App_Start/Startup.Auth.cs#L54-L82

IIS Change WebApi ConnectionString

we are using webApi for one of our newest products which is hosted on IIS7.5 and written in ASP.NET5 (.Net Core).
In earlier web-applications it was possible to change the connectionstring in the web.config in windows-Explorer and the website running on IIS used the ConnectionString in the web.config file.
Is this still possible for modern WebAPIs (I have the ConnectionString insite appsettings.json)? I did not find a solution for that inside IIS or File-Explorer and using Environment-Variables do not fit our needs.
We need to switch between several DB-Instances so a very light file-based solution would be very welcome.
PS: We are using EntityFrameworkCore (aka EF7) Database-First as it is a new tool that is on top of our current database.
You can use one of configuration sources (including JSON, accessed by AddJsonFile() in the package Microsoft.Extensions.Configuration.Json) to read the settings file and then use values read from there to configure EF.
Example code could look like this:
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json");
Configuration = builder.Build();
}
public IConfigurationRoot Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<MyDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
}
For more information see Configuration in ASP.NET Core docs or this answer.

Use SignalR along with ASP.Net WebAPI

I read a lot about SignalR and wondering about how to use it with ASP.NET WebAPI. It seems that the WebAPI route config made the SignalR connection not able to connect to Hub and I don't know how to set up correctly to make this 2 things work together.
The two should not conflict if you have not configured the webapi framework to override some of SignalR default routes like ~/signalr/hubs
[assembly: OwinStartup(typeof(SignalRConfig))]
namespace MyApp.App_Start
{
public static class SignalRConfig
{
public static void Configuration(IAppBuilder app)
{
app.MapSignalR();
}
}
}
Thats what you need for signalr to hook up, and then include the client side scripts
#Scripts.Render("~/signalr/hubs") and #Scripts.Render("~/Scripts/jquery.signalR-{version}.js")
Here is an example were I use them together
https://github.com/AndersMalmgren/SignalR.EventAggregatorProxy/tree/master/SignalR.EventAggregatorProxy.Demo.MVC4

Web API Self hosting from a test assembly

I'm currently evaluating WebAPI and NancyFx for a new project about to start. I've managed to get Nancy to self host from a test assembly (by itself it uses asp.net hosting).
Is there any way to do the same with Web API? I would like to keep the web api project hosted on IIS, but i would like to spin it up from my test assembly, so i can run tests against it.
I have found some blogposts on how to use Autofac to scan controllers from another assembly (seems a little backwards only to get hosting from another assembly to work, but if it can be done, i guess that would be an option), but i would like to keep using Structuremap ioc for this project.
Managed to get it working with help from Mark Jones link. This is what i ended up with in my test assembly.
private static HttpSelfHostServer _server;
[BeforeTestRun]
public static void Setup()
{
var config = new HttpSelfHostConfiguration(Settings.TestUri);
WebApiConfig.Register(config); //map routes
IocConfig.Bootstrap(config); //configure dependency injection
_server = new HttpSelfHostServer(config);
_server.OpenAsync().Wait();
}
[AfterTestRun]
public static void TearDown()
{
_server.CloseAsync().Wait();
}

Resources