Pages

Tuesday, March 5, 2019

Token in Web API C#.Net

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using WebApplication27.Models;

namespace WebApplication27.Controllers
{
    public class EmployeeController : Controller
    {
        // GET: Employee
        public ActionResult Index()
        {
            HttpClient obj = new HttpClient();
            obj.BaseAddress = new Uri("http://localhost:64430/api/");
            obj.DefaultRequestHeaders.Clear();
            obj.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            //Now Apply HttpVerbs
            IEnumerable<string> empList;
            HttpResponseMessage response = obj.GetAsync("employee").Result;
            empList = response.Content.ReadAsAsync<IEnumerable<string>>().Result;
            ViewBag.temp = empList;
            return View();
        }

        public ActionResult sendtoken()
        {


            using (var client = new HttpClient { BaseAddress = new Uri("http://localhost:64430/") })
            {
               //client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                var token = client.PostAsync("Token",
                    new FormUrlEncodedContent(new[]
                    {
                     new KeyValuePair<string,string>("grant_type","password"),
                     new KeyValuePair<string,string>("username","user"),
                     new KeyValuePair<string,string>("password","user")
                    })).Result.Content.ReadAsAsync<AuthenticationToken>().Result;

                client.DefaultRequestHeaders.Authorization =
                       new AuthenticationHeaderValue(token.token_type, token.access_token);

                Task<HttpResponseMessage> m = client.GetAsync("api/Account");
                Task<string> values = m.Result.Content.ReadAsStringAsync();
                ViewBag.temp = values.Result;
                return View();
            }
        }
    }
}

No comments:

Post a Comment