简体   繁体   中英

How can I use my Web Api project from other projects inside my solution?

I am developing a ASP.NET Web Api and a ASP.NET Website. The website will make use of the Web Api and a mobile app will also be using the Web Api via REST.

Developing these two separately is going fine, however I am now at the stage where I would like to start testing the Web Api from the Website, ideally all from within visual studio. For instance, I have a page where I have a form, that when completed would call my Web Api to add a user to the database.Uploading these online for testing is naturally out of the question.

So what is the best practice here? Can you simply reference the Web Api from within the Website project (Aspx) or is there another way to go about this.

Access to Web API controllers and actions are based on urls. So now that they are on separate projects you need to run both projects at the same time to make your API available for MVC project.

and by the way you should enable CORS for your web api project so that you can access it from your MVC project .

Use the below code to consume web api project

    public async Task <ActionResult> Index()
    {
        using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri("http://localhost:54568/");
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            HttpResponseMessage response = await client.GetAsync("api/Values/"); //API controller name
            if (response.IsSuccessStatusCode)
            {
                var result = await response.Content.ReadAsAsync<YourReturnDataType>();
                if (result != null)
                    var output = result;
            }
        }

        return View("Return your model here");
    }

It depends what you want to test. If you want to simply test your controller implementations you can create a test project and reference the project, manually instantiate your controllers, and invoke them in your tests.

If you want to do integration tests over the network, you can self-host the web api service. Then install the web api client package Install-Package Microsoft.AspNet.WebApi.Client in the test project and invoke via the client.

Example linking and manual instantiation (from link):

[TestClass]
public class TestSimpleProductController
{
    [TestMethod]
    public void GetAllProducts_ShouldReturnAllProducts()
    {
        var testProducts = GetTestProducts();
        var controller = new SimpleProductController(testProducts);

        var result = controller.GetAllProducts() as List<Product>;
        Assert.AreEqual(testProducts.Count, result.Count);
    }

Example using the web api client (from link):

using (var client = new HttpClient())
{
    client.BaseAddress = new Uri("http://localhost:9000/");
    client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Accept.Add(new                 MediaTypeWithQualityHeaderValue("application/json"));

    // New code:
    HttpResponseMessage response = await client.GetAsync("api/products/1");
    if (response.IsSuccessStatusCode)
    {
        Product product = await response.Content.ReadAsAsync>Product>();
        Console.WriteLine("{0}\t${1}\t{2}", product.Name, product.Price, product.Category);
    }
}

For self hosting the service:

http://www.asp.net/web-api/overview/hosting-aspnet-web-api/use-owin-to-self-host-web-api

For the Web Api client :

Install-Package Microsoft.AspNet.WebApi.Client

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