WEB API CALL FROM CLIENT MVC C#

Download
_________________________________________________________________________________


Step1: create [MVC client project]
Step2:// User.cs [Model class]
 public class User
    {
        public string UserName { get; set; }
        public string Password { get; set; }
    }
Step3://CALLPACKAGE.cs class
  public class CallPackage
    {
        public CallPackage()
        {
            Encoding = DefaultEncoding;
            EndPointUrl = string.Empty;
            Parameters = string.Empty;
            Method = HttpVerbs.Get;
            ContentType = "application/json";
            PostData = string.Empty;
        }

        public CallPackage(string endpointUrl)
            : this()
        {
            EndPointUrl = endpointUrl;
        }

        public CallPackage(string endpoint, HttpVerbs method)
            : this(endpoint)
        {
            Method = method;
        }

        public CallPackage(string endpoint, HttpVerbs method, string postData)
            : this(endpoint, method)
        {
            PostData = postData;
        }

        public string EndPointUrl { get; set; }

        public HttpVerbs Method { get; set; }

        public string ContentType { get; set; }

        public string PostData { get; set; }
        public string Parameters { get; set; }
        public Encoding Encoding { get; set; }
        public static Encoding DefaultEncoding = Encoding.GetEncoding("iso-8859-1");
    }

Step4: // call web api from [HTTPPOST LoginPost] after you click login button, to authenticate entered credentials.
 [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public ActionResult LoginPost(User obj)
        {
            if (ModelState.IsValid)
            {
                var user = AuthenticateUser(obj);
                if (user == null)
                {
                    ModelState.AddModelError("", "Invalid username or password.");
                }
            }
       
            return View();
        }

Step5:// create the api call
  public string AuthenticateUser(User authenticateUserData)
        {
            var url = GetUrl("WebAPI", "AuthenticateUser");

            var authenticateUserJson = JsonConvert.SerializeObject(authenticateUserData);
            var callPackageData = new CallPackage(url, HttpVerbs.Post, authenticateUserJson);
            var authentication = ExecString(callPackageData);
            return authentication;
        }
      
        public string GetUrl(string host, string key)
        {
           //[WEB.config =  <add key="WebAPI" value="http://localhost:000000/" />]
            string hostConfig = ConfigurationManager.AppSettings[host];
            string url = hostConfig + key;
            return url;
        }

        public string ExecString(CallPackage callPackage)
        {
            var request = (HttpWebRequest)WebRequest.Create(callPackage.EndPointUrl + callPackage.Parameters);

            request.Method = callPackage.Method.ToString();
            request.ContentLength = 0;
            request.ContentType = callPackage.ContentType;

            if (!string.IsNullOrEmpty(callPackage.PostData) && callPackage.Method == HttpVerbs.Post)
            {
                byte[] bytes = callPackage.Encoding.GetBytes(callPackage.PostData);
                request.ContentLength = bytes.Length;

                using (Stream writeStream = request.GetRequestStream())
                {
                    writeStream.Write(bytes, 0, bytes.Length);
                }
            }

            using (var response = (HttpWebResponse)request.GetResponse())
            {
                if (response.StatusCode != HttpStatusCode.OK)
                {
                    string message = String.Format("Request failed. Received HTTP {0}", response.StatusCode);
                    throw new ApplicationException(message);
                }
                // grab the response
                StreamReader reader = new StreamReader(response.GetResponseStream());
                //// Read the content.
                string responseFromServer = reader.ReadToEnd();
                return responseFromServer;
            }
        }

_________________________________________________________________________________

Comments

Popular posts from this blog

JWT - Token based authentication