{"id":21534661,"url":"https://github.com/danesparza/owin-webapi-service","last_synced_at":"2025-02-26T03:16:26.778Z","repository":{"id":13624528,"uuid":"16317788","full_name":"danesparza/OWIN-WebAPI-Service","owner":"danesparza","description":":white_check_mark: OWIN / WebAPI windows service example.  Includes attribute based routing sample","archived":false,"fork":false,"pushed_at":"2023-02-24T08:23:58.000Z","size":500,"stargazers_count":207,"open_issues_count":2,"forks_count":54,"subscribers_count":17,"default_branch":"master","last_synced_at":"2025-02-19T01:11:22.642Z","etag":null,"topics":["c-sharp","example","example-project","handler","microsoft","nuget","owin","owin-webapi-service","windows-service"],"latest_commit_sha":null,"homepage":"","language":"C#","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/danesparza.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2014-01-28T16:34:16.000Z","updated_at":"2024-11-21T08:35:22.000Z","dependencies_parsed_at":"2024-11-24T04:00:17.789Z","dependency_job_id":null,"html_url":"https://github.com/danesparza/OWIN-WebAPI-Service","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/danesparza%2FOWIN-WebAPI-Service","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/danesparza%2FOWIN-WebAPI-Service/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/danesparza%2FOWIN-WebAPI-Service/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/danesparza%2FOWIN-WebAPI-Service/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/danesparza","download_url":"https://codeload.github.com/danesparza/OWIN-WebAPI-Service/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":240783138,"owners_count":19856780,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["c-sharp","example","example-project","handler","microsoft","nuget","owin","owin-webapi-service","windows-service"],"created_at":"2024-11-24T03:12:15.489Z","updated_at":"2025-02-26T03:16:26.748Z","avatar_url":"https://github.com/danesparza.png","language":"C#","funding_links":[],"categories":[],"sub_categories":[],"readme":"OWIN WebAPI Service example [![Build status](https://ci.appveyor.com/api/projects/status/qyo52t5ipvxqh5fb?svg=true)](https://ci.appveyor.com/project/danesparza/owin-webapi-service) [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)\n===========================\n\nSometimes, you just need a good example to get started.  \n\nThe [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. \n\n*Please be aware that OWIN (and this project template) are only compatible with .NET 4.5 and newer projects.* \n\n## If starting from scratch:\n\n### Create the service project ###\nIf you're starting from scratch, add a new service project to your solution by selecting **'Windows Service'** in the new project template.\n\n### Add the OWIN Nuget packages ###\n\nFrom the package manager console: \n\n```powershell\nInstall-Package Microsoft.AspNet.WebApi.OwinSelfHost\n```\n\nThis will install the following dependent packages automatically:\n* Microsoft.AspNet.WebApi.Client\n* Microsoft.AspNet.WebApi.Core\n* Microsoft.AspNet.WebApi.Owin\n* Microsoft.AspNet.WebApi.OwinSelfHost\n* Microsoft.Owin\n* Microsoft.Owin.Host.HttpListener\n* Microsoft.Owin.Hosting\n* Newtonsoft.Json\n* Owin\n\n### Create an OWIN configuration handler\nCreate the file `Startup.cs` and put a configuration handler in it:\n\n```CSharp\nclass Startup\n{\n    //  Hack from http://stackoverflow.com/a/17227764/19020 to load controllers in \n    //  another assembly.  Another way to do this is to create a custom assembly resolver\n    Type valuesControllerType = typeof(OWINTest.API.ValuesController);\n\n    // This code configures Web API. The Startup class is specified as a type\n    // parameter in the WebApp.Start method.\n    public void Configuration(IAppBuilder appBuilder)\n    {\n        // Configure Web API for self-host. \n        HttpConfiguration config = new HttpConfiguration();\n        \n        //  Enable attribute based routing\n        //  http://www.asp.net/web-api/overview/web-api-routing-and-actions/attribute-routing-in-web-api-2\n        config.MapHttpAttributeRoutes();\n\n        config.Routes.MapHttpRoute(\n            name: \"DefaultApi\",\n            routeTemplate: \"api/{controller}/{id}\",\n            defaults: new { id = RouteParameter.Optional }\n        );\n\n        appBuilder.UseWebApi(config);\n    } \n}\n```\n    \nNote that:\n* 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/)\n* You can use Attribute based routing by including the line `config.MapHttpAttributeRoutes()` before the default `config.Routes.MapHttpRoute`\n\n### Add API controllers\nAdd API controllers to the service project by creating classes inherited from `ApiController`.  Here is a simple example that uses attribute based routing:\n\n```CSharp\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\nusing System.Web.Http;\n\nnamespace OWINTest.Service.API\n{\n    [RoutePrefix(\"api/testing\")]\n    public class RoutedController : ApiController\n    {\n        [Route(\"getall\")]\n        public IEnumerable\u003cstring\u003e GetAllItems()\n        {\n            return new string[] { \"value1\", \"value2\" };\n        }\n    }\n}\n```\n\nNote that:\n* Controllers in the service assembly will be loaded automatically.\n* 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)\n\n### Add code to start/stop the WebAPI listener\n\nAdd 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:\n\n```CSharp\npublic partial class APIServiceTest : ServiceBase\n{\n    public string baseAddress = \"http://localhost:9000/\";\n    private IDisposable _server = null;\n    \n    public APIServiceTest()\n    {\n        InitializeComponent();\n    }\n\n    protected override void OnStart(string[] args)\n    {\n        _server = WebApp.Start\u003cStartup\u003e(url: baseAddress);\n    }\n\n    protected override void OnStop()\n    {\n        if(_server != null)\n        {\n            _server.Dispose();\n        }\n        base.OnStop();\n    }\n}\n```\n\nSee how simple that is?  \n* In the `OnStart` handler, we start the listener and pass our `Startup` class we created.  That calls our configuration handler.\n* In the `OnStop` handler, we just stop the listener\n* The service will be listening with a base location of `http://localhost:9000`.\n\n### Install the service\nCreate 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.  \n\nAfter 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.\n\n### Stuff to try\nNow that you've compiled and installed your service, start it up in the 'Services' app in the control panel.  \n* 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.  \n* Try hitting breakpoints in your running service in Visual Studio by selecting 'Debug/Attach to Process'.  Select your running service exe, then press 'Attach'.  \n* 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))\n\n## Tips\n\n### Building the sample service\n\nSo 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.\n\nBefore 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...'\n\nYou 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.\n\nTry your build again after that, and you should be good.\n\n### Installing the service\n\nYou'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\u0026MSPPError=-2147217396), or use [other interesting tricks](http://stackoverflow.com/a/12401075/19020)\n\n### Serving more than just localhost\n\nIf you want to listen to all requests coming in a certain port -- not just localhost requests, you'll need to know a few things.  \n\n**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. \n\n**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`.  \n\n**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: \n\n```bash\nnetsh http add urlacl url=http://+:9000/ user=\"Local Service\"\n```\n\nWithout this, you'll have problems starting the service and listening to all requests for that port.\n\n### Help -- I'm getting Error 1053 when trying to start the service\n\nIf 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.\n\n\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdanesparza%2Fowin-webapi-service","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fdanesparza%2Fowin-webapi-service","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdanesparza%2Fowin-webapi-service/lists"}