简体   繁体   中英

WEB API Self Host Client Read Issue

I am trying to Self Host WEB API like this example: http://www.asp.net/web-api/overview/older-versions/self-host-a-web-api

Things from the ProductController pull fine:

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));
    }
}

On the Client I can print the by calling the Self Hosted Service:

    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);
        }
    }

However I am now trying to add my own controller that works in a similar way but pulls data from the database.

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;
    }

}

When doing a similar call I get an error:

    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);
        }
    }

The error is: An unhandled exception of type 'System.Net.Http.HttpRequestException' occurred in System.Net.Http.dll

Additional information: Response status code does not indicate success: 404 (Not Found). on this line resp.EnsureSuccessStatusCode();

I don't understand what the Difference is. I'm using the same format why am I getting this error.

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

public class ForemanController : ApiController

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM