【发布时间】:2014-07-16 14:44:08
【问题描述】:
我正在尝试在没有 mvc 的简单 asp.net 应用程序中运行一个简单的 restfull 服务器(按照本教程:http://www.codeproject.com/Articles/769671/Web-API-without-MVC (这将变成一个在线门户)。
这是我的课:
public class Foods
{
public string FoodName { get; set; }
public string Price { get; set; }
public string Type { get; set; }
public string Content { get; set; }
public Foods()
{
}
}
这是我的控制器:
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;
}
}
这是我的asp.net页面代码(很简单,没什么可显示的):
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();
}
}
}
当我运行它时没有错误并且显示空白页
这是一个带有列表框和按钮的简单 c# 表单的客户端:
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)
{
// Parse the response body. Blocking!
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();
}
}
但是当我运行客户端并单击按钮时,我收到此错误:
System.AggregateException:发生一个或多个错误。
System.Net.Sockets.SocketException:无法建立连接 因为目标机器主动拒绝了 127.0.0.1:8080
【问题讨论】:
-
这个受保护的 SO 问题可能会给你一些想法:No connection could be made because the target machine actively refused it?.
标签: c# asp.net-web-api