Using IIS as a service provider, you can call Windows internal Rasdial system to connect, disconnect, and check the status of VPN connections.
Rasdial.exe (http://technet.microsoft.com/en-us/library/ff859533(v=ws.10)) is an internal program which Windows uses to create VPN connections. It’s command line interface can also be used to disconnect a connection or check what connections are currently active. This is a small wrapper website that calls Rasdial, in order to handle VPN connections from a remote location through http.
To set this up, you’ll need an ASP.NET MVC website, and a few changes. This example is using IIS 7.5, ASP.NET MVC 4, on .NET 4.5.
Once the basic ASP.NET MVC website is created, the updates are:
1) Change the Default route:
routes.MapRoute(
name: "Default",
url: "{action}/{id}",
defaults: new { controller = "Vpn", action = "Disconnect", id = UrlParameter.Optional }
);
2) Add a VpnController for the default route to use:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Timers;
using System.Web;
using System.Web.Mvc;
namespace mpfiles.VpnReset.Controllers
{
public class VpnController : Controller
{
private const string DefaultName = "vpn connection name";
public ActionResult Disconnect(string name = DefaultName)
{
var arguments = string.Format("\"{0}\" /d", name);
return HandleRasDial(arguments);
}
public ActionResult Connect(
string name = DefaultName,
string username = "username",
string password = "password"
) {
var arguments = string.Format("\"{0}\" {1} {2}", name, username, password);
return HandleRasDial(arguments);
}
public ActionResult Status(string name = DefaultName)
{
return HandleRasDial(string.Empty);
}
public ActionResult HandleRasDial(string arguments)
{
var startTime = DateTime.Now;
var message = RasDial(arguments);
message = message.Replace("\n", "<br />");
var endTime = DateTime.Now;
message += "<br />" + String.Format("[{0}]", (endTime - startTime));
return new ContentResult { Content = message };
}
public string RasDial(string arguments)
{
var proc = new Process();
proc.StartInfo.FileName = "rasdial";
proc.StartInfo.WorkingDirectory = HttpContext.Request.PhysicalApplicationPath;
proc.StartInfo.Arguments = arguments;
proc.StartInfo.RedirectStandardError = true;
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.CreateNoWindow = true;
proc.EnableRaisingEvents = false;
proc.Start();
var output = proc.StandardOutput.ReadToEnd();
output += proc.StandardError.ReadToEnd();
proc.WaitForExit();
proc.Dispose();
return output;
}
}
}
I hope someone else will find this useful.