Create a new console app in Xamarin.

Add nuget package Microsoft ASP.NET Web API 2.2 OWIN Self Host

Start an webapp in program.cs

 1 public static void Main (string[] args)
 2 {
 3 	var host = "http://localhost:9000";
 4 	using(WebApp.Start(host))
 5 	{
 6 		Console.WriteLine ("Server running on " + host);
 7 		Console.WriteLine ("Press any key to shutdown.");
 8 		Console.ReadLine ();
 9 	}
10 }

Run the app and it’ll complain that we need to create a Startup class, let’s create it.

Create a new class file called Startup.cs in the root of our app.

 1 public class Startup
 2 {
 3 	public void Configuration(IAppBuilder appBuilder) 
 4 	{ 
 5 		var config = new HttpConfiguration(); 
 6 
 7 		config.Routes.MapHttpRoute( 
 8 			name: "DefaultApi", 
 9 			routeTemplate: "api/{controller}/{id}", 
10 			defaults: new { id = RouteParameter.Optional } 
11 		); 
12 
13 		appBuilder.UseWebApi(config); 
14 	}
15 }

Now everything is set, let’s start creating our controllers.

Create a new class file ValuesController.cs inside Controllers folder just for a bit of organization.

1 public class ValuesController : ApiController
2 {
3 	public IEnumerable<string> Get()
4 	{
5 		return new[] { "value1", "value2", "value3" };
6 	}
7 }

Run the app and now you should access the address http://localhost:9000/api/values and see a response with the values in the controller. Probably the response is a xml document, let’s change it to json.

Add this line to the Startup class.

config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue(“text/html”) );

Note that with this method response’s Content-Type will still be “text/html” if you need the response as “application/json” see this Stackoverflow thread

The code for this project can be found here

Fork me on GitHub