[RESOLVED]Comsume a web api in a MVC application

Hi,

I have a Web App which is using a Web Api (Both are diff projects under same solution). I need to add/host this Solution to IIS.

Should i deploy both as different websites? If yes, then after deploy how to call web api methods from web application?

Hi Harry,

                 You can’t host solution to IIS. Publish both of your project and host separately in the IIS.
Now you can access web api methods in your Web app. Refer this code:

    protected string Url = "http://localhost/webapi/api/Controller/Action";
    public ActionResult Index() 
    {       
        WebClient client = new WebClient();        
        DataModelClass result = JsonConvert.DeserializeObject<DataModelClass>(client.DownloadString(url));
        return View(result);
    }

Thanks,

Avishek

Mark as Answer, if it helps you.

You need to deploy the two projects separately in IIS. In web app, use web.config to configure webapi url. Inside the code behind, use this configuration value.

HttpClient

client =
new
HttpClient();

HttpClient client = new HttpClient();
// Controller constructor, initialize client with url obtained from web.config
public HomeController()
        {
            client.BaseAddress = new Uri(ConfigurationManager.AppSettings["AZDocPortalUrl"]);
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            loggerService = new LoggerService();
        }
// call webapi inside action methods
public ActionResult Index()
{
HttpResponseMessage response = client.GetAsync("api/home/GetById?userName=" + user).Result;
}

Leave a Reply