WebAPI 2.2 and Trace.axd - asp.net-web-api

I'm using WebApi 2.2 and have installed the WebApi 2.2 Tracing package.
In my WebApiConfig.Register method, I have added this line:
config.EnableSystemDiagnosticsTracing();
I'd like to write out some information to trace.axd in my action methods, like what I used to do with ASP.NET webform.
Something like:
[Route("getCurrentUser")]
[HttpPost]
public IHttpActionResult GetCurrentUser()
{
Trace.WriteLine("GetCurrentUser"); // doesn't work
Configuration.Services.GetTraceWriter().Warn(
Request, "AccountController", "GetCurrentUser"); // doesn't work either
}
However I'm not seeing anything in trace.axd.
I do see the info logged in visual studio though, when I debug it, but it's writing out too much information which I don't need.
What I really want is to only see the trace information I specifically write in my action methods.
Thanks!!

When you enable that, it creates a new instance of SystemDiagnosticsTraceWriter class. The default TraceLevel is Info so your Warn should work.
By default, the SystemDiagnosticsTraceWriter writes traces to System.Diagnostics.Trace and they are written in the Output window of the Visual Studio. So you should register additional Trace Listeners.
You should configure it in your web config where to write the tracing logic to?
I'm guessing the Trace.axd is the ASP.NET Trace Viewer and works with ASP.NET Pages. not sure whether it can work with Web API.
But you can configure a different trace listener e.g. to Event Log or Console, or File or your custom trace writer:
<system.diagnostics>
<trace autoflush="false" indentsize="4">
<listeners>
<add name="eventLogListener"
type="System.Diagnostics.EventLogTraceListener"
initializeData="TraceListenerLog" />
<add name="logFileListener"
type="System.Diagnostics.TextWriterTraceListener"
initializeData="E:\CompressedLogs\Service1-WebApi-TraceOutput.log" />
<remove name="Default" />
</listeners>
</trace>
</system.diagnostics>

Great question, I'm choosing an Web API tracing component and the first one that pops to mind is ASP.NET Tracing, as it is easy to enable/disable and secure. There's no need to install additional packages; the ASP.NET Trace can be used through System.Web.HttpContext.Current:
using System.Web;
...
catch(Exception e)
{
HttpContext.Current.Trace.Warn("MyWebAPI", string.Format("[ERROR] {0}", e));
}
Remember to enable trace in web.config:
<trace enabled="true" pageOutput="false" localOnly="true" requestLimit="200" />
I aways use pageOutput="false" localOnly="true" because I think it's the most secure trace configuration (other than being disabled ;-): there's no trace output on the pages, and the trace can be viewed only by a browser running on the server.
If you need to view the trace on production enviroments, remember to turn it off after you use it.

Related

iis hosting WCF Service

I trying host my project, but when I run svc file then i get exception.
Exception data: System.InvalidOperationException: The convention requires the use of Session, but the "BasicHttpBinding" binding is not supported or is not configured correctly.
What could be the problem?
I tried changing the web.config file but I don't know what the problem is
You can change your binding mode from BasicHttpBinding to WsHttpBinding. Since the default binding method for HTTP is BasicHttpBinding, you can modify it in the <System.ServiceModel>:
<protocolMapping>
<add scheme="http" binding="wsHttpBinding" bindingConfiguration="WsHttpSession"/>
</protocolMapping>
This allows you to modify the binding.

B2C Authentication with WebForms

I have a legacy WebForms application. I need to add Azure B2C authentication to it. My application is using currently Microsoft.Aspnet.Identity. It does not have any startup.cs page. How can I make this migration?
Some minor things allow you to switch your site to use AAD or aadb2c for authentication.
Get the necessary OWIN NuGet packages, Add some startup code to use the OWIN authentication libraries ,Register your application in AADb2c.
Update your web.config with appropriate OAuth values.
Even though OWIN didn’t exist when you wrote your Web Forms app, you can still use it and it will significantly simplify the process.
In the Visual Studio menu, select Tools > NuGet Package Manager > Package Manager Console.
Make sure your web project is selected in the Default project drop down.
Run the below commands:
install-package Microsoft.Owin.Host.SystemWeb
install-package Microsoft.Owin.Security.OpenIdConnect
install-package Microsoft.Owin.Security.Cookies
You may check the references and then follow this B2C-WebForms-DotNet
References:
c# - ASP.NET Web Api - Startup.cs doesn't exist - Stack
Overflow
c# - OWIN Startup Class Missing - Stack Overflow
edit:
My web forms if for visual C# and could find owin start up :
Right click on App_Start > add item > under web , you can find it.
Please check if your project is visual c# .
edit 2:
Please check if below points help :
Maybe you can create new start up class by using owin library in the clas
Imports Microsoft.Owin.Extensions
Imports Microsoft.Owin.Security
Imports Microsoft.Owin.Security.Cookies
Imports Microsoft.Owin.Security.OpenIdConnect
Imports Owin
Imports System
Imports System.Configuration
Check the web.config file and remove this key setting and try
<add key="owin:AutomaticAppStartup" value="false" />
and also try add <add key="owin:AutomaticAppStartup" value="true " /> in web.config file
The following attribute will set the startup class to the StartUp class in the StartupDemo namespace.
[assembly: OwinStartup(typeof(StartupDemo.StartUp))]
Add appSetting element in the Configuration file
<appSettings>
<add key="owin:appStartup" value="StartupDemo.StartUp" />
</appSettings>
Check how owin detects start up owin-startup-class-detection -Microsoft docs
Other references:
owin-startup-class-not-detected
owin-with-vb-net-legacy-code-asp-net-web-forms
where-to-implement-startup-code-in-vb-net

Asp.Net Web Api Logging

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)

How to disable custom error page generation in IIS server

My Spring Boot application running on IIS Server generating custom error page for remote request finding error code 401 at header. I want to disable it. There should be no custom error page in response data. Desired behavior is there as default in Apache server. Though IIS Server can be configured to prevent generating custom error page for remote request, I want it to be configured from my application (Web Configuration point may be). Is it possible in Spring?
In your web.xml add this:
<error-page>
<error-code>401</error-code>
<location>/errors/unauthorised</location>
</error-page>
Then add a controller like this:
#Controller
#RequestMapping("/errors")
public class ApplicationExceptionHandler {
#ResponseStatus(HttpStatus.UNAUTHORIZED)
#RequestMapping("unauthorised")
public ModelAndView unauthorizedError(){
return new ModelAndView("errors/error.jsp");
}
}
Add a web.config file to your app's webapp directory (app/src/main/webapp). web.config file should consist:
<configuration>
<system.webServer>
<httpErrors errorMode="Detailed" existingResponse="Auto" />
</system.webServer>
</configuration>
this will cause IIS web server to set error mode to 'Detailed' which will prevent generating custom error page.

Trouble with session attributes getting replicated in Tomcat 6

I have configured Tomcat 6 with in-memory session replication. I am also using IIS 7 (I know, I know) and the AJP connector via isapi_redirector. The cluster is working properly and I am able to replicate session attributes using the SessionExample in the examples war. The problem is that I am unable to do the same in my custom application. I have added the distributable tag to the web.xml file on both servers in my test cluster. However, I don't see any message in the logs mentioning the attributes getting sent to the cluster (I see them for SessionExample). The only primary differences that I can see in my app from the examples:
The examples war uses servlet 2.5. I am still required to use 2.4.
My application uses SSO and requires the user to login.
The application is a portal application.
Also, in the code of the application, I am setting a simple string in the attribute, so nothing fancy.
So, I was wondering if anyone has some tips to get this working?
Thanks
Here is the cluster section within of my server.xml:
<Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster"
channelSendOptions="6">
<Manager className="org.apache.catalina.ha.session.DeltaManager"
expireSessionsOnShutdown="false"
notifyListenersOnReplication="true"/>
<Channel className="org.apache.catalina.tribes.group.GroupChannel">
<Membership className="org.apache.catalina.tribes.membership.McastService"
address="228.0.0.104"
port="45564"
frequency="500"
dropTime="10000"/>
<Receiver className="org.apache.catalina.tribes.transport.nio.NioReceiver"
address="auto"
port="4000"
autoBind="100"
selectorTimeout="7000"
maxThreads="6"
timeout="15000"/>
<Sender className="org.apache.catalina.tribes.transport.ReplicationTransmitter">
<Transport className="org.apache.catalina.tribes.transport.nio.PooledParallelSender"
timeout="70000"/>
</Sender>
<Interceptor className="org.apache.catalina.tribes.group.interceptors.TcpFailureDetector"/>
<Interceptor className="org.apache.catalina.tribes.group.interceptors.MessageDispatch15Interceptor"/>
</Channel>
<Valve className="org.apache.catalina.ha.tcp.ReplicationValve"
filter=".*\.gif;.*\.js;.*\.jpg;.*\.png;.*\.htm;.*\.html;.*\.css;.*\.txt;"/>
<Valve className="org.apache.catalina.ha.session.JvmRouteBinderValve"/>
<Deployer className="org.apache.catalina.ha.deploy.FarmWarDeployer"
tempDir="/apache-tomcat-6.0.37/war-deploy/war-temp/"
deployDir="/apache-tomcat-6.0.37/webapps/"
watchDir="/apache-tomcat-6.0.37/war-deploy/war-listen/"
watchEnabled="true"/>
<ClusterListener className="org.apache.catalina.ha.session.JvmRouteSessionIDBinderListener"/>
<ClusterListener className="org.apache.catalina.ha.session.ClusterSessionListener"/>
</Cluster>
Sorry. I found the issue. I was expecting to see messages in the log regarding the creation of the session attributes. I didn't realize that the examples project had a session listener that was outputting the messages to the log. I was thinking that it was simply from the log level that I had set.
Thanks to anyone who read this post.

Resources