Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/26.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/kotlin/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# WEB API自主机客户端读取问题_C#_Sql Server_Asp.net Web Api - Fatal编程技术网

C# WEB API自主机客户端读取问题

C# WEB API自主机客户端读取问题,c#,sql-server,asp.net-web-api,C#,Sql Server,Asp.net Web Api,我正在尝试自我托管WEB API,如以下示例所示: ProductController中的内容很好: public class ProductsController : ApiController { Product[] products = new Product[] { new Product { Id = 1, Name = "Tomato Soup", Category = "Groceries", Price = 1 },

我正在尝试自我托管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));
    }
}
公共类产品控制器:ApiController
{
产品[]产品=新产品[]
{  
新产品{Id=1,Name=“番茄汤”,Category=“杂货”,Price=1},
新产品{Id=2,Name=“Yo”,Category=“Toys”,Price=375万},
新产品{Id=3,Name=“Hammer”,Category=“Hardware”,Price=16.99M}
};
公共IEnumerable GetAllProducts()
{
退货产品;
}
公共产品GetProductById(int id)
{
var product=products.FirstOrDefault((p)=>p.Id==Id);
如果(产品==null)
{
抛出新的HttpResponseException(HttpStatusCode.NotFound);
}
退货产品;
}
公共IEnumerable GetProductsByCategory(字符串类别)
{
返回产品。其中(p=>string.Equals)(p.Category,Category,
StringComparison(Ordinalingorecase));
}
}
在客户端上,我可以通过调用自托管服务打印:

    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);
        }
    }
static void Main(字符串[]args)
{
client.BaseAddress=新Uri(“http://localhost:8080");
列出所有产品();
控制台。WriteLine(“按Enter键退出”);
Console.ReadLine();
}
静态void ListAllProducts()
{
HttpResponseMessage resp=client.GetAsync(“api/products”).Result;
resp.EnsuccessStatusCode();
var products=resp.Content.ReadAsAsync().Result;
foreach(产品中的var p)
{
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;
    }

}
class-ForemanController:ApiController
{
静态领班[]所有领班;
静态SqlConnectionStringBuilder connectionString=new-SqlConnectionStringBuilder();
公共工头控制员()
{
connectionString.DataSource=“dxdb02v”;
connectionString.InitialCatalog=“QTRAX4619410”;
connectionString.UserID=“tunnelld”;
connectionString.Password=“david”;
string queryString=“从[QTRAXAdmin].[vwQT_Foreman]中选择*”;
名单;
//创建SQL连接
使用(var connection=new SqlConnection(connectionString.ToString()))
{
使用(var命令=新的SqlCommand(queryString,connection))
{
connection.Open();
使用(var reader=command.ExecuteReader())
{
列表=新列表();
while(reader.Read())
{
添加(新的领班{foreback=reader.GetString(0),ForeName=reader.GetString(1)});
}
}
}
connection.Close();
allForeman=list.ToArray();
}
}
公共IEnumerable GetAllForeman()
{
返回所有领班;
}
}
在进行类似呼叫时,我收到一个错误:

    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);
        }
    }
static void Main(字符串[]args)
{
client.BaseAddress=新Uri(“http://localhost:8080");
ListalForeman();
控制台。WriteLine(“按Enter键退出”);
Console.ReadLine();
}
静态void ListAllForeman()
{
HttpResponseMessage resp=client.GetAsync(“api/foreman”).Result;
resp.EnsuccessStatusCode();
var foreman=resp.Content.ReadAsAsync().Result;
foreach(领班中的var f)
{
Console.WriteLine(“{0}{1}”,f.foreback,f.ForeName);
}
}
错误是:System.Net.Http.dll中发生类型为“System.Net.Http.HttpRequestException”的未处理异常

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


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

我认为您的控制器类需要是公共的

public class ForemanController : ApiController

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

public class ForemanController : ApiController

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

public class ForemanController : ApiController

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

public class ForemanController : ApiController