1

I need to call console to web application method in C#.

my code is below-

Console application code:

public static class Program
    {
       public static void Main(String[] args)
        {
         Console.Write("Waiting for call getData method...");
         Console.Read();
        }
    }

Web Application Code :

public class MyController : BaseController
    {

    [HttpGet]
    public string getData(string data)
    {
       return data;
    }
}

I just need call getData(data) method from console.

PLease suggest.

HarryDev
  • 61
  • 2
  • 12
  • 1
    refer this http://stackoverflow.com/a/4988325/7036750 – Prasanna Kumar J Jan 21 '17 at 05:07
  • Considering a real-world scenario, your web application should run independently possibly inside a web server e.g. IIS. Then console application being a client should call the exposed web methods through the mechanism @PrasannaKumarJ has correctly suggested. If you want to literally refer the web project into your console application then you can follow the standard mechanism of adding a reference to a project in Visual Studio as suggested by RIdwan Galib in his answer. A web project is just like any other C# project with some additional info so that it can be published to a web server. – RBT Jan 21 '17 at 05:45

2 Answers2

2

you can do this using system.net.http. Have a look at this MSDN article.

Calling WebAPI from Console app

Do not get into RunAsync and all. Just use HTTPClient to call API.

Here is the complete code example. .................................

using System;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;

namespace HttpClientSample
{
public class Product
{
    public string Id { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }
    public string Category { get; set; }
}

class Program
{
    static HttpClient client = new HttpClient();

    static void ShowProduct(Product product)
    {
        Console.WriteLine($"Name: {product.Name}\tPrice: {product.Price}\tCategory: {product.Category}");
    }

    static async Task<Uri> CreateProductAsync(Product product)
    {
        HttpResponseMessage response = await client.PostAsJsonAsync("api/products", product);
        response.EnsureSuccessStatusCode();

        // return URI of the created resource.
        return response.Headers.Location;
    }

    static async Task<Product> GetProductAsync(string path)
    {
        Product product = null;
        HttpResponseMessage response = await client.GetAsync(path);
        if (response.IsSuccessStatusCode)
        {
            product = await response.Content.ReadAsAsync<Product>();
        }
        return product;
    }

    static async Task<Product> UpdateProductAsync(Product product)
    {
        HttpResponseMessage response = await client.PutAsJsonAsync($"api/products/{product.Id}", product);
        response.EnsureSuccessStatusCode();

        // Deserialize the updated product from the response body.
        product = await response.Content.ReadAsAsync<Product>();
        return product;
    }

    static async Task<HttpStatusCode> DeleteProductAsync(string id)
    {
        HttpResponseMessage response = await client.DeleteAsync($"api/products/{id}");
        return response.StatusCode;
    }

    static void Main()
    {
        RunAsync().Wait();
    }

    static async Task RunAsync()
    {
        client.BaseAddress = new Uri("http://localhost:55268/");
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

        try
        {
            // Create a new product
            Product product = new Product { Name = "Gizmo", Price = 100, Category = "Widgets" };

            var url = await CreateProductAsync(product);
            Console.WriteLine($"Created at {url}");

            // Get the product
            product = await GetProductAsync(url.PathAndQuery);
            ShowProduct(product);

            // Update the product
            Console.WriteLine("Updating price...");
            product.Price = 80;
            await UpdateProductAsync(product);

            // Get the updated product
            product = await GetProductAsync(url.PathAndQuery);
            ShowProduct(product);

            // Delete the product
            var statusCode = await DeleteProductAsync(product.Id);
            Console.WriteLine($"Deleted (HTTP Status = {(int)statusCode})");

        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
        }

        Console.ReadLine();
    }

}
}
kevalsing
  • 196
  • 8
  • May I request you to please add some more context around your answer. Link-only answers are difficult to understand and are susceptible to become invalid if the website is down or not working. It will help the asker and future readers both if you can reproduce the most relevant portions of the link/blog you are referring to into this post itself. – RBT Jan 21 '17 at 05:46
1

Both are different application, so you can add web application as reference of console application and then just create a object to access getData(data)