【问题标题】:WEB API Self Host Client Read IssueWEB API Self Host Client 读取问题
【发布时间】:2015-05-19 20:34:44
【问题描述】:

我正在尝试像以下示例一样自托管 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.Http.dll 中出现“System.Net.Http.HttpRequestException”类型的未处理异常

附加信息:响应状态码不表示成功:404(未找到)。在这条线上resp.EnsureSuccessStatusCode();

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

【问题讨论】:

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


    【解决方案1】:

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

    public class ForemanController : ApiController
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-12-14
      • 2014-05-01
      • 2012-01-22
      • 1970-01-01
      • 2013-02-24
      • 1970-01-01
      • 2021-10-15
      • 1970-01-01
      相关资源
      最近更新 更多