WEB API自主客户端读取问题

时间:2015-05-19 20:34:44

标签: c# sql-server asp.net-web-api

我正在尝试自我主机WEB API,如下例所示: http://www.asp.net/web-api/overview/older-versions/self-host-a-web-api

来自ProductController的东西很好:

public class ProductsController : ApiController
{
    Product[] products = new Product[]  
        {  
            new Product { Id = 1, Name = "Tomato Soup", Category = "Groceries", Price = 1 },  
            new Product { Id = 2, Name = "Yo-yo", Category = "Toys", Price = 3.75M },  
            new Product { Id = 3, Name = "Hammer", Category = "Hardware", Price = 16.99M }  
        };

    public IEnumerable<Product> GetAllProducts()
    {
        return products;
    }

    public Product GetProductById(int id)
    {
        var product = products.FirstOrDefault((p) => p.Id == id);
        if (product == null)
        {
            throw new HttpResponseException(HttpStatusCode.NotFound);
        }
        return product;
    }

    public IEnumerable<Product> GetProductsByCategory(string category)
    {
        return products.Where(p => string.Equals(p.Category, category,
                StringComparison.OrdinalIgnoreCase));
    }
}

在客户端,我可以通过调用自助托管服务来打印:

    static void Main(string[] args)
    {
        client.BaseAddress = new Uri("http://localhost:8080");

        ListAllProducts();

        Console.WriteLine("Press Enter to quit.");
        Console.ReadLine();
    }

    static void ListAllProducts()
    {
        HttpResponseMessage resp = client.GetAsync("api/products").Result;
        resp.EnsureSuccessStatusCode();

        var products = resp.Content.ReadAsAsync<IEnumerable<SelfHost.Product>>().Result;
        foreach (var p in products)
        {
            Console.WriteLine("{0} {1} {2} ({3})", p.Id, p.Name, p.Price, p.Category);
        }
    }

但是我现在正在尝试添加我自己的控制器,它以类似的方式工作,但从数据库中提取数据。

class ForemanController : ApiController
{
    static Foreman[] allForeman;
    static SqlConnectionStringBuilder connectionString = new SqlConnectionStringBuilder();


    public ForemanController()
    {
        connectionString.DataSource = "dxdb02v";
        connectionString.InitialCatalog = "QTRAX4619410";
        connectionString.UserID = "tunnelld";
        connectionString.Password = "david";

        string queryString = "SELECT * FROM [QTRAXAdmin].[vwQT_Foreman]";

        List<Foreman> list;
        // Creates a SQL connection
        using (var connection = new SqlConnection(connectionString.ToString()))
        {
            using (var command = new SqlCommand(queryString, connection))
            {
                connection.Open();
                using (var reader = command.ExecuteReader())
                {
                    list = new List<Foreman>();
                    while (reader.Read())
                    {
                        list.Add(new Foreman { ForeBadge = reader.GetString(0), ForeName = reader.GetString(1) });
                    }
                }
            }
            connection.Close();
            allForeman = list.ToArray();
        }
    }

    public IEnumerable<Foreman> GetAllForeman()
    {
        return allForeman;
    }

}

在进行类似的通话时,我收到错误:

    static void Main(string[] args)
    {
        client.BaseAddress = new Uri("http://localhost:8080");

        ListAllForeman();

        Console.WriteLine("Press Enter to quit.");
        Console.ReadLine();
    }

    static void ListAllForeman()
    {
        HttpResponseMessage resp = client.GetAsync("api/foreman").Result;
        resp.EnsureSuccessStatusCode();

        var foreman = resp.Content.ReadAsAsync<IEnumerable<SelfHost.Foreman>>().Result;
        foreach (var f in foreman)
        {
            Console.WriteLine("{0} {1}", f.ForeBadge, f.ForeName);
        }
    }

错误是:#System; Net.Net.Http.HttpRequestException类型的未处理异常&#39;发生在System.Net.Http.dll

其他信息:响应状态代码不表示成功:404(未找到)。在这一行resp.EnsureSuccessStatusCode();

我不明白差异是什么。我使用相同的格式为什么会出现此错误。

1 个答案:

答案 0 :(得分:3)

我相信您的控制器类需要公开

public class ForemanController : ApiController