Tag Archives: asp.net

.NET Aspire and Antivirus

Adding Antivirus to .NET Aspire Systems

I was working on a web application over the weekend and I needed to add a feature that would allow images to be uploaded by end-users. As we all know, we should never trust content uploaded by anonymous ‘friends’ on the internet. I wanted to add malware scanning to my project, but how? In this article, I introduce a proof-of-concept project that adds the open source ClamAV antivirus scanner to a .NET Aspire system and shares connection information so that other resources can request malware scans.

The idea

I stumbled on a medium article by Jeroen Verhaeghe where the ClamAV antivirus scanner was introduced in combination with the nClam library from Ryan Hoffman.  Jeroen shows us how the ClamAV scanner can be run in a Docker container, and in reading that I thought – why not let .NET Aspire manage the container and its communications for us?

The Proof of Concept Code

ClamAV publishes a self-maintaining docker container that updates itself with latest malware definitions. We know that containers can be added to a .NET Aspire project, so I wrote a quick resource that shared an HttpEndpoint:

Now we’re talking! We can now reference a ClamAV container resource easily in our .NET Aspire AppHost project and pass it to our website like this:

.NET Aspire Dashboard showing the ClamAV antivirus resource

We can now scan our uploaded files with the nClam library like this:

That’s pretty easy to get started with… and there’s a lot more that we can do with this to help make our public file uploads secure by default.

Get the Code!

I’ve published my sample code, showing a Blazor application uploading files to a minimal API endpoint where ClamAV inspects the content and reports back whether malware was detected. You can find it on my GitHub at https://github.com/csharpfritz/AspireAntivirus

What do you think? Is this something that I should spend some more time wrapping and making easier to use? Create an issue on the GitHub repository if there’s something I can improve or a comment below to let me know what you think.

WebForms – How do I Unit Test Thee?

I’m a huge fan of unit testing… its my safety net, allowing me to make changes to an application without fear that I’ve broken core functionality. With my favorite web development framework, ASP.NET, its been very difficult to build unit tests for the server-side code that you write for the Web Forms UI framework.

I decided to do some research and start doing something about that.

Continue reading

Where Did My ASP.NET Bundles Go in ASP.NET 5?

Stuffed BagEdit: There is now a screencast version of this post available.

Since ASP.NET 4.5 in 2012, developers have had access to a pair of tools in their ASP.NET toolbox called “bundling and minification”.  This feature would direct the webserver to combine together CSS or JavaScript files into one extra-large file and then apply a minification algorithm to shrink the size of the file for delivery.  In ASP.NET 5 however, this feature is no longer available.  In this article, I’ll review where bundles were configured and how you can migrate them to the recommended deployment model for ASP.NET 5

Continue reading

That Annoying ASP.NET Issue with Postback

Stop me if you’ve heard this before:

I’m working through an ASP.NET project and suddenly Postback stops working.  I know!  This is the simplest of interactions with an ASP.NET web forms application, and its not WORKING!!  What the heck is wrong with this stupid website?  I mean, I didn’t change anything.. I just want my default.aspx form to be able to have a button click button handler.  Is that so DIFFICULT?  Get your act together FRITZ!1!!

I did some digging and digging on this one.  Did I bring in an add-in or library to my project that was preventing the postback from capturing the click event?  I broke out Fiddler and analyzed the traffic, to ensure that the form content was indeed being submitted properly back to the server.  Everything looked good there.

My next analysis step was to take a look at the Request.Form collection.  I should see the __EVENTARGUMENT being populated.  When I opened the Immediate Window and inspected Request.Form, this is what I found:

How is the Request.Form collection empty?  What’s the deal with THAT?

I started thinking about the ASP.NET pipeline, and it hit me:  FriendlyUrls.

There’s this interesting thing that happens when web forms attempt to post back to pages managed by FriendlyUrls and lack a filename.  This could be any of the following pages in your site:

  • /
  • /Products/
  • /Orders/

You get the idea.  These pages for some reason don’t handle postback properly.  With that in mind, I set forth to drop a quick and dirty change to enable this throughout the website.  Fortunately, I can make that change through a URL Rewrite operation.  I added the following event handler to my global.asax.cs file:

    void Application_BeginRequest(object sender, EventArgs e)
    {
      var app = (HttpApplication)sender;
      if (app.Context.Request.Url.LocalPath.EndsWith("/"))
      {
        app.Context.RewritePath(
                 string.Concat(app.Context.Request.Url.LocalPath, "default"));
      }
    }

With that, my pages started posting back properly… all was right in the world.

Please note:  you will have this problem with the default ASP.NET project with web forms when FriendlyUrls are enabled.

The Truth About HttpHandlers and WebApi

In 2012 when Microsoft introduced the ASP.Net WebAPI, I initially became confused about yet another way to generate and transmit content across a HttpRequest.  After spending some time thinking about WebAPI over the past week or two and writing a few blocks of sample code, I think I finally have some clarity around my confusion and these are those lessons I learned the hard way.

Old School API – SOAP and ASMX

When ASP.Net launched, the only framework to create and publish content that was available was WebForms.  Everybody used it, and it worked well.  If you wanted to create an interface for machine-to-machine communications you would create a SOAP service in an ASMX file.  You could (and still can) add web references to projects that reference these services.  The web reference gives you a first class object with a complete API in your project that you can interact with.

Over time, it became less compelling to build the SOAP services as they transmitted a significant amount of wrapper content around the actual payload you wanted to work with.  This extra content was messy, and other programming languages didn’t have the tooling support to manage them well.  Developers started looking for less complicated alternatives to communicate with connected clients.  It turns out that there was another option available that was overlooked by many: HttpHandlers.

HttpHandlers in ASP.Net

HttpHandlers are the backbone of ASP.Net.  An HttpHandler is any class that implements the IHttpHandler interface, handles an incoming request, and provides a response to webserver communications.  IHttpHandler is a trivial interface with the following signature:

 

    public class TestHandler : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            // TODO: Implement this method
            throw new NotImplementedException();
        }

        public bool IsReusable
        {
            get
            {
                // TODO: Implement this property getter
                throw new NotImplementedException();
            }
        }
    }

Listing 1 – Simple IHttpHandler interface implementation

The ProcessRequest method is where we can insert our code to handle all data being requested of the handler and all data to respond from the handler.  The IsReusable property is often misunderstood, but has a simple definition: Should an instance of this handler be re-used for other requests to the webserver?  If the return value is false, a new version of the handler class will be instantiated for each request to the server.  If IsReusable returns true, then the same instance will be used for all requests to the server.  A simple implementation that outputs some of my favorite sports teams in XML format might look like this:

public class MyHandler : IHttpHandler
    {


        public readonly static IEnumerable MyTeams = new List
        {
            new Team { City = "Philadelphia", Name = "Phillies" },
            new Team { City = "Boston", Name = "Red Sox" },
            new Team { City = "Cleveland", Name = "Browns" },
            new Team { City = "Houston", Name = "Astros" },
            new Team { City = "San Diego", Name = "Chargers" }
        };

        #region IHttpHandler Members

        public bool IsReusable
        {
            get { return true; }
        }

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/xml";

            context.Response.Write("");

            foreach (var t in MyData.MyTeams)
            {
                context.Response.Write("");
                context.Response.Write("");
                context.Response.Write(t.City);
                context.Response.Write("");
                context.Response.Write("");
                context.Response.Write(t.Name);
                context.Response.Write("");
                context.Response.Write("");
            }

            context.Response.Write("");

        }

        #endregion
    }

Listing 2 – A Sample XML Generating HttpHandler

Some developers get confused about the difference between a class that implements IHttpHandler and an ASHX file.  These are very similar things, but different with their own advantages.  An ASHX file is an IHttpHandler whose end-point is defined by the name of the ASHX file.  If you create foo.ashx you can trigger the ProcessRequest method by navigating to http://localhost/foo.ashx  Conversely, a class that implements IHttpHandler needs to be registered in web.config with a path and file-extension end-point to answer to.  The format of this registration lies within the system.webServer section of web.config:


    

        

    
  

Listing 3 – Web.Config entries for an HttpHandler

Further instructions on how to configure the HttpHandler is available on MSDN

Both of these types of HttpHandlers are easy to implement, and put you right on the metal.  You are handed and HttpContext and you can do anything you want to handle the incoming request and respond to it.  If you are working with some low-level operations such as inspecting HttpHeaders for responses, you may choose to go this route.

ASP.Net WebAPI in a nutshell

Scott Guthrie describes ASP.Net WebAPI as a technology that allows developers to build powerful web based APIs that have the following 9 core capabilities:

  • Modern HTTP Programming Model – Directly access the HTTP requests and responses using a strongly typed HTTP object model
  • Content Negotiation – Built in support for content negotiation, which allows the client and server to work together to determine to correct data format to return from an API
  • Query Composition – Easily supports OData URL conventions when you return a type of IQueryable<T> from a method
  • Model Binding and Validation – Supports the same model binding available in WebForms and MVC
  • Routes – You know ’em, you love ’em… they’re all over ASP.Net.  Why WOULDN’T you expect them in WebAPI?
  • Filters – You can apply similar filters to those that you create for MVC
  • Improved Testability – WebAPI uses two new objects called HttpRequestMessage and HttpResponseMessage to make unit testing significantly easier.  
  • IoC Support – The same service locator pattern implemented in ASP.Net MVC is available to inject dependencies into your API implementations
  • Flexible Hosting – Web APIs can be hosted within any type of ASP.Net application.  You can also host it within any process if you don’t want to engage IIS to host your API.

The quick and dirty summary of this list is that WebAPI functions, looks, and feels like developing with ASP.Net MVC.  There are a few simple differences between them, but once you learn them, its very easy to progress quickly.

The Super-Duper Happy Sample

To implement a simple service that outputs a collection of values when a GET is called with no arguments (eg: http://localhost/api/Values ) you need to add very little to get started.  First, add a WebAPI controller to your website by selecting the appropriate item in the Add Item dialog box:

The default implementation delivered looks like the following:

    public class ValuesController : ApiController
    {
        // GET api/<controller>
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }

        // GET api/<controller>/5
        public string Get(int id)
        {
            return "value";
        }

        // POST api/<controller>
        public void Post([FromBody]string value)
        {
        }

        // PUT api/<controller>/5
        public void Put(int id, [FromBody]string value)
        {
        }

        // DELETE api/<controller>/5
        public void Delete(int id)
        {
        }
    }

Listing 4 – Default API Controller implementation

With this simple implementation you can navigate your browser to http://localhost/api/values and get the two values “value1” and “value2” returned in XML format.  If you programatically request that address and change your “accept” header to “text/json” you will receive JSON in the response stream.  You can PUT, POST, and DELETE content to this controller and the appropriate action methods will be triggered based on the HTTP action executed.  

The Truth

WebAPI is just another HttpHandler, one that has been wrapped around all sorts of helpful content management and negotiation technologies as Scott Guthrie suggested.  You certainly could cut out all of those other technologies and benefits and code directly “on the metal” with an HttpHandler, and that was the only choice you had until 2012 and ASP.Net 4.  In today’s web community, its best to use RESTful methods and use a standard format like XML or JSON to transfer data.  HttpHandlers had their place, but going forward, I’m going to use WebAPI whenever I need to transmit data over HTTP to browsers or any other connected client.