Posts Under Tag: ASP.NET MVC

Serving Static Files Outside of wwwroot in Asp.NET Core 1.0

In ASP.NET Core 1.0 (which is out as RC2 at the time I’m writing this post), static content such as images, css files, javascript files, etc can be served up in the wwwroot folder once your web site contains the NuGet package for Microsoft.AspNetCore.StaticFiles.  But what if you wanted to serve up static files outside of wwwroot?  With a little work extending the application builder configuration, it is possible.

First, create a folder under the root (but outside of wwwroot) of the ASP.NET Core application.  In this example, I’ll name that folder ‘static’.  In this example, we’ll store static files within this folder.

Next, let’s create a static class (no pun intended) within the ASP.NET Core web application project to extend the ApplicationBuilder with a method that will allow for serving static content from this folder named ‘static’:

using System.IO;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting.Internal;
using Microsoft.Extensions.FileProviders;

public static class ApplicationBuilderExtensions
{
	public static IApplicationBuilder UseStaticResources(this IApplicationBuilder app, HostingEnvironment env)
	{
		var path = Path.Combine(env.ContentRootPath, "static"); // this allows for serving up contents in a folder named 'static'
		var provider = new PhysicalFileProvider(path);

		var options = new StaticFileOptions();
		options.RequestPath = ""; // an empty string will give the *appearance* of it being served up from the root
		//options.RequestPath = "/content"; // this will use the URL path named content, but could be any made-up name you want
		options.FileProvider = provider;

		app.UseStaticFiles(options);
		return app;
	}
}

Let’s walk through what this is doing.  On line 9 it is getting the physical path of the newly created ‘static’ folder.  Now that the app knows where these files physically reside, let’s take advantage of some optional URL routing.  Shown above on line 15, I’m setting the RequestPath to an empty string.  What that will do is re-route requests for static files in the root path of the app to the physical ‘static’ folder.  That means an HTTP request like this:

<img src='foo.img' />

will be routed to look for the foo.img file in the physical folder named ‘static’.

Alternately, if I wanted to use the ‘content’ folder name (or any other name) in HTML calls for these static resources, I could do so as shown in the commented-out line #16.  In that line, the URL would use the ‘content’ route, which doesn’t physically exist but in fact gets re-routed to the ‘content’ physical path.  In this case, the resources physically sitting in the ‘static’ folder would be accessed using that re-written path like this:

<img src='/content/foo.img' />

Finally, line 19 is needed to give your app the ability to actually serve up static files within your application (you’ll still need to have the NuGet package Microsoft.AspNetCore.StaticFiles in order to make this work).

But in order to make this all work, we need to actually use this ApplicationBuilder extension.  To do that, open up the Start.cs file of the ASP.NET Core web application.  In Start.cs there is a method named Configure that gets called at runtime and configures the HTTP request pipeline.  It is within here that the call to the UseStaticResources method is needed:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
	app.UseStaticResources((HostingEnvironment)env);
	
	//... the rest of your Configure method calls go here
}

The above line #4 calls the method you created which allows for the serving up of static files from whatever folder you designated outside of wwwroot.

Update 7/1/2016 – Microsoft released their official documentation for working with static files in ASP.NET Core; definitely worth a read.

Tags: , Filled Under: Programming Posted on: June 3, 2016

Plugging Twilio SMS in to the ASP.NET Identity Message Service

If you want to enable 2-factor authentication in ASP.NET, ASP.NET Identity and Twilio make it silly easy to do so.

Step 1: Setting Up Your Project for ASP.NET Identity
From Visual Studio, start with an ASP.NET Web Application and select the MVC Template.  In this example I’ll use the Authentication option ‘Individual User Accounts’, which under the covers is really just adding the ASP.NET Identity NuGet packages for you.  For an existing application you could manually include the ASP.NET Identity NuGet packages, but I would take a look at the ASP.NET Identity Samples App first to get familiar with what it offers.

Create an MVC project with Individual Accounts.

Create an MVC project with Individual Accounts.

Congratulations, you now have an MVC application with ASP.NET Identity management!  In the App_Start folder a class file named IdentityConfig.cs was added by the NuGet package.

The IdentityConfig.cs file has multiple classes in it (StyleCop may have something to say about that), and the one that controls SMS is named SmsService.  Scroll down to it and you’ll see a single placeholder method to send an SMS message asynchronously.

SMS Service Class

The SmsService class in IdentityConfig.cs

Step 2: Set-up Twilio for SMS
Now it’s time for Twilio!  Sign up for a free Twilio account.  To do this simply press the ‘Sign Up’ button on the Twilio site and you’ll be prompted to create an account.  The account is free and you don’t need to enter in any payment information.  During the sign-up process it will ask to verify your mobile phone number prior to assigning you a phone number in your Twilio account.

The reason for verifying your own phone number first has to do with the free trial account that gets set up.  While in trial/sandbox mode, a phone number is created and made available to you for free, however one of the limitations is it can only communicate with a number you register and verify with Twilio.  More details of how a Twilio free trial account works can be found here.

Now that you have a Twilio account and phone number, you’ll need three pieces of information to get ASP.NET Identity 2-factor authentication via SMS working: your Twilio phone number, account SID, and Auth Token.  These can be found on the Twilio Account page.  Make a note of this information.

Twilio account page

You’ll need the Account SID, Auth Token, and your Twilio assigned phone number.

Now back to the ASP.NET application that you created.  Simply install the Twilio NuGet package to add support for their API.

PM> Install-Package Twilio

In the SmsService class in IdentityConfig.cs, the TwilioRestClient will be used to send the SMS messages supporting 2-factor authentication.

public class SmsService : IIdentityMessageService
{
	public Task SendAsync(IdentityMessage message)
	{
		// Plug in your sms service here to send a text message.
		// set our AccountSid and AuthToken
		string AccountSid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
		string AuthToken = "fXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";

		// instantiate a new Twilio Rest Client
		var client = new TwilioRestClient(AccountSid, AuthToken);
		client.SendMessage("14085551111", message.Destination, message.Body);

		return Task.FromResult(0);
	}
}

In the above code, your Twilio Account SID and Auth Token are set to variables.  The TwilioRestClient takes them as parameters (more info about the TwilioRestClient can be found in this section of the Twilio docs).  The SendMessage method takes the following parameters: your Twilio assigned phone number, the recipient phone number, and the message.  The IdentityMessage object contains both the recipient (message.Destination) and the message text (message.Body).

Step 3: Using 2-factor Authentication For Your Account
Run your application and log in.  You can manage your account by clicking on your user name in the top right.  An account management screen is shown.

First add your phone number; it should be the same phone number that you verified when you created the Twilio account.

Add your phone number to your account

Click on the Add link to enter the phone number you previously verified when creating your Twilio account.

You’ll be asked to verify this phone number.  If you hooked up Twilio correctly within your app’s SmsService class, you will get a text with the verification code.  Enter that code to verify your phone number for the ASP.NET Identity service.

Enter verification code

Enter the code sent via SMS to verify your phone number.

Now enable 2-factor authentication on your account.

Enable two factor authentication for your account

Enable 2-factor authentication for your account.

To test it out, sign out of your app.  Log back in and you’ll first enter your username and password.  Next, you’ll be prompted to send a verification code for 2-factor authentication.

Enter verification code

Enter the received 2-factor verification code to complete login.

That code will be sent via SMS; enter it when prompted.  Once you press the Submit button, you’ll finally be logged in.

When you’re ready to go to production, upgrade your Twilio account and update that information in the SmsService class.

Tags: Filled Under: Programming Posted on: January 25, 2015

The Case of the Missing config File

While working on a code base that deploys to a CI environment, a “it work’s on my machine” moment occurred. In a brand new ASP.NET MVC 5 application that worked just fine locally, attempting to load any view resulted in a System.InvalidOperationException on the control environment. The exact exception was:

System.InvalidOperationException: The view at '~/Views/home/Index.cshtml' must derive from WebViewPage, or WebViewPage<TModel>.

In this particular CI environment, the deployment automation process has specific rules set up to exclude the copying of .config files. The reason for that exclusion isn’t all that important, but needless to say it’s a process that’s a work in progress. The root web.config contents are manually set on each deployment environment.

This was the first time this CI environment had an MVC deployed; it was previously set-up for ASP.NET web forms application. The root web.config was manually deployed, but it turns out the web.config in the Views folder that defines important config sections such as the one for the Razor view engine was forgotten. Once the Views web.config was deployed to the Views folder, this exception was resolved and the views began rendering.

Tags: Filled Under: Programming Posted on: April 17, 2014