Repository: danesparza/OWIN-WebAPI-Service
Branch: master
Commit: 7135b8ca6ee9
Files: 25
Total size: 49.8 KB
Directory structure:
gitextract_jqyd6uxk/
├── .gitignore
├── .nuget/
│ ├── NuGet.Config
│ └── NuGet.targets
├── LICENSE
├── OWINTest.API/
│ ├── OWINTest.API.csproj
│ ├── Properties/
│ │ └── AssemblyInfo.cs
│ ├── ValuesController.cs
│ └── packages.config
├── OWINTest.Service/
│ ├── API/
│ │ ├── PersonController.cs
│ │ └── RoutedController.cs
│ ├── APIServiceTest.Designer.cs
│ ├── APIServiceTest.cs
│ ├── App.config
│ ├── OWINTest.Service.csproj
│ ├── Program.cs
│ ├── ProjectInstaller.Designer.cs
│ ├── ProjectInstaller.cs
│ ├── ProjectInstaller.resx
│ ├── Properties/
│ │ └── AssemblyInfo.cs
│ ├── Startup.cs
│ ├── install.cmd
│ ├── packages.config
│ └── uninstall.cmd
├── OWINTest.sln
└── README.md
================================================
FILE CONTENTS
================================================
================================================
FILE: .gitignore
================================================
# Build Folders (you can keep bin if you'd like, to store dlls and pdbs)
[Bb]in/
[Oo]bj/
# mstest test results
TestResults
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
# User-specific files
*.suo
*.user
*.sln.docstates
# Build results
[Dd]ebug/
[Rr]elease/
x64/
*_i.c
*_p.c
*.ilk
*.meta
*.obj
*.pch
*.pdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.log
*.vspscc
*.vssscc
.builds
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opensdf
*.sdf
# Visual Studio profiler
*.psess
*.vsp
*.vspx
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*
# NCrunch
*.ncrunch*
.*crunch*.local.xml
# Installshield output folder
[Ee]xpress
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish
# Publish Web Output
*.Publish.xml
# NuGet Packages Directory
packages
# Windows Azure Build Output
csx
*.build.csdef
# Windows Store app package directory
AppPackages/
# Others
[Bb]in
[Oo]bj
sql
TestResults
[Tt]est[Rr]esult*
*.Cache
ClientBin
[Ss]tyle[Cc]op.*
~$*
*.dbmdl
Generated_Code #added for RIA/Silverlight projects
# Backup & report files from converting an old project file to a newer
# Visual Studio version. Backup files are not needed, because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
================================================
FILE: .nuget/NuGet.Config
================================================
================================================
FILE: .nuget/NuGet.targets
================================================
$(MSBuildProjectDirectory)\..\
false
false
true
false
$([System.IO.Path]::Combine($(SolutionDir), ".nuget"))
$(SolutionDir).nuget
$(MSBuildProjectDirectory)\packages.$(MSBuildProjectName.Replace(' ', '_')).config
$(MSBuildProjectDirectory)\packages.$(MSBuildProjectName).config
$(MSBuildProjectDirectory)\packages.config
$(PackagesProjectConfig)
$(NuGetToolsPath)\NuGet.exe
@(PackageSource)
"$(NuGetExePath)"
mono --runtime=v4.0.30319 "$(NuGetExePath)"
$(TargetDir.Trim('\\'))
-RequireConsent
-NonInteractive
"$(SolutionDir) "
"$(SolutionDir)"
$(NuGetCommand) install "$(PackagesConfig)" -source "$(PackageSources)" $(NonInteractiveSwitch) $(RequireConsentSwitch) -solutionDir $(PaddedSolutionDir)
$(NuGetCommand) pack "$(ProjectPath)" -Properties "Configuration=$(Configuration);Platform=$(Platform)" $(NonInteractiveSwitch) -OutputDirectory "$(PackageOutputDir)" -symbols
RestorePackages;
$(BuildDependsOn);
$(BuildDependsOn);
BuildPackage;
================================================
FILE: LICENSE
================================================
The MIT License (MIT)
Copyright (c) 2014 Dan Esparza
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
================================================
FILE: OWINTest.API/OWINTest.API.csproj
================================================
Debug
AnyCPU
{1671F393-642C-46EA-9FA7-58F53818E724}
Library
Properties
OWINTest.API
OWINTest.API
v4.5
512
..\
true
true
full
false
bin\Debug\
DEBUG;TRACE
prompt
4
pdbonly
true
bin\Release\
TRACE
prompt
4
..\packages\Newtonsoft.Json.4.5.11\lib\net40\Newtonsoft.Json.dll
False
..\packages\Microsoft.AspNet.WebApi.Client.5.1.0\lib\net45\System.Net.Http.Formatting.dll
False
..\packages\Microsoft.AspNet.WebApi.Core.5.1.0\lib\net45\System.Web.Http.dll
This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.
================================================
FILE: OWINTest.API/Properties/AssemblyInfo.cs
================================================
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("OWINTest.API")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("OWINTest.API")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("d611539e-d658-4ebf-948e-98cc39d62ccf")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
================================================
FILE: OWINTest.API/ValuesController.cs
================================================
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http;
namespace OWINTest.API
{
public class ValuesController : ApiController
{
// GET api/values
public IEnumerable Get()
{
return new string[] { "value1", "value2" };
}
// GET api/values/5
public string Get(int id)
{
return "value";
}
// POST api/values
public void Post([FromBody]string value)
{
}
// PUT api/values/5
public void Put(int id, [FromBody]string value)
{
}
// DELETE api/values/5
public void Delete(int id)
{
}
}
}
================================================
FILE: OWINTest.API/packages.config
================================================
================================================
FILE: OWINTest.Service/API/PersonController.cs
================================================
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http;
namespace OWINTest.Service.API
{
public class PersonController : ApiController
{
// GET api/values
public IEnumerable Get()
{
return new string[] { "value1", "value2" };
}
// GET api/values/5
public string Get(int id)
{
return "value";
}
// POST api/values
public void Post([FromBody]string value)
{
}
// PUT api/values/5
public void Put(int id, [FromBody]string value)
{
}
// DELETE api/values/5
public void Delete(int id)
{
}
}
}
================================================
FILE: OWINTest.Service/API/RoutedController.cs
================================================
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http;
namespace OWINTest.Service.API
{
[RoutePrefix("api/testing")]
public class RoutedController : ApiController
{
[Route("getall")]
public IEnumerable GetAllItems()
{
return new string[] { "value1", "value2" };
}
}
}
================================================
FILE: OWINTest.Service/APIServiceTest.Designer.cs
================================================
namespace OWINTest.Service
{
partial class APIServiceTest
{
///
/// Required designer variable.
///
private System.ComponentModel.IContainer components = null;
///
/// Clean up any resources being used.
///
/// true if managed resources should be disposed; otherwise, false.
protected override void Dispose(bool disposing)
{
if(disposing)
{
if (_server != null)
{
_server.Dispose();
}
if (components != null)
{
components.Dispose();
}
}
base.Dispose(disposing);
}
#region Component Designer generated code
///
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
///
private void InitializeComponent()
{
components = new System.ComponentModel.Container();
this.ServiceName = "Service1";
}
#endregion
}
}
================================================
FILE: OWINTest.Service/APIServiceTest.cs
================================================
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Owin.Hosting;
namespace OWINTest.Service
{
public partial class APIServiceTest : ServiceBase
{
public string baseAddress = "http://localhost:9000/";
private IDisposable _server = null;
public APIServiceTest()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
_server = WebApp.Start(url: baseAddress);
}
protected override void OnStop()
{
if(_server != null)
{
_server.Dispose();
}
base.OnStop();
}
}
}
================================================
FILE: OWINTest.Service/App.config
================================================
================================================
FILE: OWINTest.Service/OWINTest.Service.csproj
================================================
Debug
AnyCPU
{040449FC-D996-49AF-BD74-D137D5688992}
WinExe
Properties
OWINTest.Service
OWINTest.Service
v4.5
512
..\
true
AnyCPU
true
full
false
bin\Debug\
DEBUG;TRACE
prompt
4
AnyCPU
pdbonly
true
bin\Release\
TRACE
prompt
4
..\packages\Microsoft.Owin.2.0.2\lib\net45\Microsoft.Owin.dll
..\packages\Microsoft.Owin.Host.HttpListener.2.0.2\lib\net45\Microsoft.Owin.Host.HttpListener.dll
..\packages\Microsoft.Owin.Hosting.2.0.2\lib\net45\Microsoft.Owin.Hosting.dll
False
..\packages\Newtonsoft.Json.4.5.11\lib\net40\Newtonsoft.Json.dll
..\packages\Owin.1.0\lib\net40\Owin.dll
False
..\packages\Microsoft.AspNet.WebApi.Client.5.1.0\lib\net45\System.Net.Http.Formatting.dll
False
..\packages\Microsoft.AspNet.WebApi.Core.5.1.0\lib\net45\System.Web.Http.dll
..\packages\Microsoft.AspNet.WebApi.Owin.5.1.0\lib\net45\System.Web.Http.Owin.dll
Component
APIServiceTest.cs
Component
ProjectInstaller.cs
PreserveNewest
PreserveNewest
{1671f393-642c-46ea-9fa7-58f53818e724}
OWINTest.API
ProjectInstaller.cs
This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.
================================================
FILE: OWINTest.Service/Program.cs
================================================
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
namespace OWINTest.Service
{
static class Program
{
///
/// The main entry point for the application.
///
static void Main()
{
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new APIServiceTest()
};
ServiceBase.Run(ServicesToRun);
}
}
}
================================================
FILE: OWINTest.Service/ProjectInstaller.Designer.cs
================================================
namespace OWINTest.Service
{
partial class ProjectInstaller
{
///
/// Required designer variable.
///
private System.ComponentModel.IContainer components = null;
///
/// Clean up any resources being used.
///
/// true if managed resources should be disposed; otherwise, false.
protected override void Dispose(bool disposing)
{
if(disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Component Designer generated code
///
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
///
private void InitializeComponent()
{
this.serviceProcessInstaller1 = new System.ServiceProcess.ServiceProcessInstaller();
this.serviceInstaller1 = new System.ServiceProcess.ServiceInstaller();
//
// serviceProcessInstaller1
//
this.serviceProcessInstaller1.Account = System.ServiceProcess.ServiceAccount.LocalService;
this.serviceProcessInstaller1.Password = null;
this.serviceProcessInstaller1.Username = null;
//
// serviceInstaller1
//
this.serviceInstaller1.DisplayName = "OWIN Service Test";
this.serviceInstaller1.ServiceName = "OWINServiceTest";
this.serviceInstaller1.AfterInstall += new System.Configuration.Install.InstallEventHandler(this.serviceInstaller1_AfterInstall);
//
// ProjectInstaller
//
this.Installers.AddRange(new System.Configuration.Install.Installer[] {
this.serviceProcessInstaller1,
this.serviceInstaller1});
}
#endregion
private System.ServiceProcess.ServiceProcessInstaller serviceProcessInstaller1;
private System.ServiceProcess.ServiceInstaller serviceInstaller1;
}
}
================================================
FILE: OWINTest.Service/ProjectInstaller.cs
================================================
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration.Install;
using System.Linq;
using System.Threading.Tasks;
namespace OWINTest.Service
{
[RunInstaller(true)]
public partial class ProjectInstaller : System.Configuration.Install.Installer
{
public ProjectInstaller()
{
InitializeComponent();
}
private void serviceInstaller1_AfterInstall(object sender, InstallEventArgs e)
{
}
}
}
================================================
FILE: OWINTest.Service/ProjectInstaller.resx
================================================
text/microsoft-resx
2.0
System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
17, 56
196, 17
False
================================================
FILE: OWINTest.Service/Properties/AssemblyInfo.cs
================================================
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("OWINTest.Service")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("OWINTest.Service")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("3c680edc-55b3-4c07-885e-15adc849c05e")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
================================================
FILE: OWINTest.Service/Startup.cs
================================================
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http;
using Owin;
namespace OWINTest.Service
{
class Startup
{
// Hack from http://stackoverflow.com/a/17227764/19020 to load controllers in
// another assembly. Another way to do this is to create a custom assembly resolver
Type valuesControllerType = typeof(OWINTest.API.ValuesController);
// This code configures Web API. The Startup class is specified as a type
// parameter in the WebApp.Start method.
public void Configuration(IAppBuilder appBuilder)
{
// Configure Web API for self-host.
HttpConfiguration config = new HttpConfiguration();
// Enable attribute based routing
// http://www.asp.net/web-api/overview/web-api-routing-and-actions/attribute-routing-in-web-api-2
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
appBuilder.UseWebApi(config);
}
}
}
================================================
FILE: OWINTest.Service/install.cmd
================================================
path = %path%;C:\Windows\Microsoft.NET\Framework\v4.0.30319;
installutil OWINTest.Service.exe
pause
================================================
FILE: OWINTest.Service/packages.config
================================================
================================================
FILE: OWINTest.Service/uninstall.cmd
================================================
path = %path%;C:\Windows\Microsoft.NET\Framework\v4.0.30319;
installutil /u OWINTest.Service.exe
pause
================================================
FILE: OWINTest.sln
================================================
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 2013
VisualStudioVersion = 12.0.30110.0
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "OWINTest.Service", "OWINTest.Service\OWINTest.Service.csproj", "{040449FC-D996-49AF-BD74-D137D5688992}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "OWINTest.API", "OWINTest.API\OWINTest.API.csproj", "{1671F393-642C-46EA-9FA7-58F53818E724}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = ".nuget", ".nuget", "{A89D3C9D-EDE8-4518-92A7-045C5DB112A5}"
ProjectSection(SolutionItems) = preProject
.nuget\NuGet.Config = .nuget\NuGet.Config
.nuget\NuGet.exe = .nuget\NuGet.exe
.nuget\NuGet.targets = .nuget\NuGet.targets
EndProjectSection
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{040449FC-D996-49AF-BD74-D137D5688992}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{040449FC-D996-49AF-BD74-D137D5688992}.Debug|Any CPU.Build.0 = Debug|Any CPU
{040449FC-D996-49AF-BD74-D137D5688992}.Release|Any CPU.ActiveCfg = Release|Any CPU
{040449FC-D996-49AF-BD74-D137D5688992}.Release|Any CPU.Build.0 = Release|Any CPU
{1671F393-642C-46EA-9FA7-58F53818E724}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{1671F393-642C-46EA-9FA7-58F53818E724}.Debug|Any CPU.Build.0 = Debug|Any CPU
{1671F393-642C-46EA-9FA7-58F53818E724}.Release|Any CPU.ActiveCfg = Release|Any CPU
{1671F393-642C-46EA-9FA7-58F53818E724}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal
================================================
FILE: README.md
================================================
OWIN WebAPI Service example [](https://opensource.org/licenses/MIT)
===========================
Sometimes, you just need a good example to get started.
The [OWIN-WebAPI-Service project](https://github.com/danesparza/OWIN-WebAPI-Service) came out of a need to create a self-hosted WebAPI 2 service in a Windows service. Microsoft says that going forward, [OWIN is the way to go](http://www.asp.net/web-api/overview/hosting-aspnet-web-api/self-host-a-web-api). I wanted to use [attribute routing](http://www.asp.net/web-api/overview/web-api-routing-and-actions/attribute-routing-in-web-api-2) in WebAPI 2. I couldn't find a decent example anywhere, so I created my own.
*Please be aware that OWIN (and this project template) are only compatible with .NET 4.5 and newer projects.*
## If starting from scratch:
### Create the service project ###
If you're starting from scratch, add a new service project to your solution by selecting **'Windows Service'** in the new project template.
### Add the OWIN Nuget packages ###
From the package manager console:
```powershell
Install-Package Microsoft.AspNet.WebApi.OwinSelfHost
```
This will install the following dependent packages automatically:
* Microsoft.AspNet.WebApi.Client
* Microsoft.AspNet.WebApi.Core
* Microsoft.AspNet.WebApi.Owin
* Microsoft.AspNet.WebApi.OwinSelfHost
* Microsoft.Owin
* Microsoft.Owin.Host.HttpListener
* Microsoft.Owin.Hosting
* Newtonsoft.Json
* Owin
### Create an OWIN configuration handler
Create the file `Startup.cs` and put a configuration handler in it:
```CSharp
class Startup
{
// Hack from http://stackoverflow.com/a/17227764/19020 to load controllers in
// another assembly. Another way to do this is to create a custom assembly resolver
Type valuesControllerType = typeof(OWINTest.API.ValuesController);
// This code configures Web API. The Startup class is specified as a type
// parameter in the WebApp.Start method.
public void Configuration(IAppBuilder appBuilder)
{
// Configure Web API for self-host.
HttpConfiguration config = new HttpConfiguration();
// Enable attribute based routing
// http://www.asp.net/web-api/overview/web-api-routing-and-actions/attribute-routing-in-web-api-2
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
appBuilder.UseWebApi(config);
}
}
```
Note that:
* You can load API controllers from another assembly by using the hack `Type valuesControllerType = typeof(OWINTest.API.ValuesController);` or by creating a [custom assembly resolver](http://www.strathweb.com/2013/08/customizing-controller-discovery-in-asp-net-web-api/)
* You can use Attribute based routing by including the line `config.MapHttpAttributeRoutes()` before the default `config.Routes.MapHttpRoute`
### Add API controllers
Add API controllers to the service project by creating classes inherited from `ApiController`. Here is a simple example that uses attribute based routing:
```CSharp
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http;
namespace OWINTest.Service.API
{
[RoutePrefix("api/testing")]
public class RoutedController : ApiController
{
[Route("getall")]
public IEnumerable GetAllItems()
{
return new string[] { "value1", "value2" };
}
}
}
```
Note that:
* Controllers in the service assembly will be loaded automatically.
* If you want to load a controller in another assembly, you'll need to update your `Startup.cs` file (and read the note about loading controllers from other assemblies, above)
### Add code to start/stop the WebAPI listener
Add code to the default service (inherited from `ServiceBase`) that the Visual Studio template created for you. The finished service class should look something like this:
```CSharp
public partial class APIServiceTest : ServiceBase
{
public string baseAddress = "http://localhost:9000/";
private IDisposable _server = null;
public APIServiceTest()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
_server = WebApp.Start(url: baseAddress);
}
protected override void OnStop()
{
if(_server != null)
{
_server.Dispose();
}
base.OnStop();
}
}
```
See how simple that is?
* In the `OnStart` handler, we start the listener and pass our `Startup` class we created. That calls our configuration handler.
* In the `OnStop` handler, we just stop the listener
* The service will be listening with a base location of `http://localhost:9000`.
### Install the service
Create a service installer by right-clicking on the service design surface and selecting 'Add installer' from the context menu. You can update the service name, description, [startup mode](http://superuser.com/a/285655/4508) and [default credentials](http://stackoverflow.com/a/510225/19020) by updating the properties on the 2 new controls that are added.
After you've [added the service installer](http://msdn.microsoft.com/en-us/library/ddhy0byf(v=vs.110).aspx) by updating the service code, install the service using the [.NET installutil.exe](http://msdn.microsoft.com/en-us/library/50614e95(v=vs.110).aspx). See the sample batch files `install.cmd` and `uninstall.cmd` for an example of making this a little easier on yourself.
### Stuff to try
Now that you've compiled and installed your service, start it up in the 'Services' app in the control panel.
* If you've added the `RoutedController` example above, try navigating to the following url in [Postman](http://www.getpostman.com/) or your favorite REST service tester: `http://localhost:9000/api/testing/getall` -- you should get a JSON string array back.
* Try hitting breakpoints in your running service in Visual Studio by selecting 'Debug/Attach to Process'. Select your running service exe, then press 'Attach'.
* Try calling the service directly from a browser-based single page application. (Hint: You won't be able to until you [enable CORS](http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api))
## Tips
### Building the sample service
So if you just want to take a look at the sample project, you'll need to either grab the zip or [clone the project](https://help.github.com/articles/which-remote-url-should-i-use/) in git.
Before you build and install the service you'll need to do a 'Nuget package restore'. The easiest way to do this is probably to right-click on the solution in Visual Studio and select 'Manage Nuget packages for solution...'
You should see the 'Manage NuGet Packages' screen pop up. At the very top of the screen, you'll probably see a yellow message indicating that 'Some NuGet packages are missing from this solution. Click to restore from your online package sources.' with a Restore button. Go ahead and click Restore and then close the window once the missing packages have been downloaded.
Try your build again after that, and you should be good.
### Installing the service
You'll need to run the `installutil` command as an Administrator. To do that, you'll need to [run the command prompt itself as Administrator](https://technet.microsoft.com/en-us/library/cc947813%28v=ws.10%29.aspx?f=255&MSPPError=-2147217396), or use [other interesting tricks](http://stackoverflow.com/a/12401075/19020)
### Serving more than just localhost
If you want to listen to all requests coming in a certain port -- not just localhost requests, you'll need to know a few things.
**First**, understand [there are permission differences between Local System, Local service, Network service](http://stackoverflow.com/a/510225/19020), and a user account. I recommend you run under 'Local service' because it's a minimal set of permissions.
**Second**, you'll need to change the code that starts the service. Instead of listening for requests to `http://localhost:9000`, you'll need to listen for requests to `http://+:9000`.
**Third**, you'll need to use the command-line tool `netsh` to authorize 'Local Service' to listen for requests. I usually put this command in the **install.bat** file that installs the service:
```bash
netsh http add urlacl url=http://+:9000/ user="Local Service"
```
Without this, you'll have problems starting the service and listening to all requests for that port.
### Help -- I'm getting Error 1053 when trying to start the service
If you're getting `Error 1053: The service did not respond to the start or control request in a timely fashion.` there is a good chance you don't have the right version of the .NET framework installed. Remember: OWIN and WebAPI 2 require .NET 4.5 or a more recent version of the framework to be installed.