I'm trying to run a simple restfull server in a simple asp.net application without the mvc(following this tutorial : http://www.codeproject.com/Articles/769671/Web-API-without-MVC (which will trun into a online portal).
here is my class :
public class Foods
{
public string FoodName { get; set; }
public string Price { get; set; }
public string Type { get; set; }
public string Content { get; set; }
}
and here is my controller:
public class FoodController : ApiController
{
public List<Foods> _productList;
public List<Foods> GetProductList()
{
_productList = new List<Foods>{
new Foods{FoodName= "pizza",Content= "bread cheese",Type="Main",Price="100"},
new Foods{FoodName= "rice",Content= "rice and ...",Type="Main",Price="100"}
};
return _productList;
}
}
and here is my asp.net page code(it is simple nothing to show):
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
var config = new HttpSelfHostConfiguration("http://localhost:8080/");
config.Routes.MapHttpRoute(
"API Default", "api/{controller}/{id}",
new { id = System.Web.Http.RouteParameter.Optional });
using (HttpSelfHostServer server = new HttpSelfHostServer(config))
{
server.OpenAsync().Wait();
}
}
}
when i run it there is no error and the blank page is shown
and here is the client which is a simple c# form with a list box and a button:
private void button1_Click(object sender, EventArgs e)
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:8080/");
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
try
{
HttpResponseMessage response = client.GetAsync("api/foods").Result;
if (response.IsSuccessStatusCode)
{
var foods = response.Content.ReadAsAsync<IEnumerable<Foods>>().Result;
foreach (Foods food in foods)
{
string foodinfo = food.FoodName + " " + food.Content + " " + food.Type + " " + food.Price;
listBox1.Items.Add(foodinfo);
}
}
}
catch (Exception ex)
{
textBox1.Text = ex.ToString();
}
}
but when i run the client and click the button i get this error:
Object reference not set to an instance of an object.
and the page i saying source is not available