Sunday, May 3, 2015

Create and consume WCF Restful Service using an HttpClient

Restful Services are getting more and more popular in our days and .NET developers prefer to build them through the Web API Framework, which let’s be honest it sounds right. You need to know though that WCF Framework also provides the support for building services that can be consumed over HTTP requests. This post will show you how easy is to create a WCF Restful service and consume it, either from a simple browser typing the right URL or from another application using an HttpClient.
Open Visual Studio and create a new WCF Service Application named WcfRestfulService. At this very moment, VS has created for you a WCF service using the default binding. You can test it by right clicking the Service1.svc file and view it on browser. We are going to change that service in order to be able to invoke it using HTTP requests.

Change Service1.svc to AdminLoginService.svc.cs.There is also IAdminLoginService.cs

AdminLoginService

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using BusinessLogic;
using System.ServiceModel.Activation;
using System.IO;
using System.Collections.Specialized;
using System.Web;
using System.Data;
using BusinessObject;

namespace AppWcfService
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "AdminLoginService" in code, svc and config file together.
    [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall, AddressFilterMode = AddressFilterMode.Any)]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class AdminLoginService : IAdminLoginService
    {
        MessageFormat mf = new MessageFormat();
        public List<GETADMINUNIQ> AdminLogin(Stream input)
        {
            string message = string.Empty;
            string login_identity = string.Empty;
            string login_password = string.Empty;
            var streamReader = new StreamReader(input);
            string streamString = streamReader.ReadToEnd();
            streamReader.Close();

            GETADMINUNIQ getadminuniq  = new GETADMINUNIQ();
            GETADMINUNIQlist adminlist = new GETADMINUNIQlist();


            NameValueCollection nvc = HttpUtility.ParseQueryString(streamString);
            login_identity = string.IsNullOrEmpty(nvc["login_identity"]) ? "" : nvc["login_identity"];
            login_password = string.IsNullOrEmpty(nvc["login_password"]) ? "" : nvc["login_password"];
            int LoginID = 0;
            try
            {
                if (login_identity != null && login_password != null)
                {
                    LoginID = user_accountsBL.LOGINaccounts(login_identity, login_password);
                    if (LoginID > 0)
                    {
                        DataTable dtuniq = user_accountsBL.Get_UniqAftrLogin(LoginID);

                        getadminuniq.uniqueid = dtuniq.Rows[0][0].ToString();
                        adminlist.GETADMINUNIQDetailsList.Add(getadminuniq);
                        return adminlist.GETADMINUNIQDetailsList;
                       
                    }
                    else
                    {
                      
                        return adminlist.GETADMINUNIQDetailsList;
                      
                    }
                   
                }
                else
                {
                  
                    return adminlist.GETADMINUNIQDetailsList;
                }

               
            }
            catch
            {
               
                return adminlist.GETADMINUNIQDetailsList;
            }
         
        }


        public MessageFormat FORGOTPASSWORD(Stream input)
        {
            string message = string.Empty;
            string Email = string.Empty;
            string Uniqueid = string.Empty;
            string pwd = string.Empty;
            string fname = string.Empty;
            var streamReader = new StreamReader(input);
            string streamString = streamReader.ReadToEnd();
            streamReader.Close();

            NameValueCollection nvc = HttpUtility.ParseQueryString(streamString);
            Email = string.IsNullOrEmpty(nvc["Email"]) ? "" : nvc["Email"];
            Uniqueid = string.IsNullOrEmpty(nvc["Uniqueid"]) ? "" : nvc["Uniqueid"];


            try
            {
                DataTable dt1 = user_accountsBL.GetPAssword(Email, Uniqueid);
                if (dt1.Rows.Count > 0)
                {
                    //check uniqueid

                    if (dt1.Rows[0][user_accounts.F_uacc_password].ToString() == "-5")
                    {
                        message = "Uniqueid Not Exists";
                        mf.Message = message;
                        return mf;
                    }
                    else if (dt1.Rows[0][user_accounts.F_uacc_password].ToString() == "-1")
                    {
                        message = "Email Not Exists";
                        mf.Message = message;
                        return mf;
                    }
                    else
                    {
                        pwd = dt1.Rows[0][user_accounts.F_uacc_password].ToString();
                        fname = dt1.Rows[0][user_accounts.F_upro_first_name].ToString();

                        string msg = " <b> Dear " + fname + ",</b> <br> <br> <br> </t> Your Password is :" + " " + pwd + " <br> <br> <b> Best Regards</b>,<br><br> <b> Admin</b>";
                        bool res = user_profilesBL.SendEmail("PASSWORD RECOVERY", msg, Email);
                        if (res == true)
                        {
                            message = "Success";
                            mf.Message = message;
                            return mf;
                        }
                        else
                        {
                            message = "Error";
                            mf.Message = message;
                            return mf;
                        }
                    }
                }
                else
                {
                    message = "Not Exists";
                    mf.Message = message;
                    return mf;
                }

               
              
            }
            catch
            {
                message = "Error";
                mf.Message = message;
                return mf;
            }
        }
    }
}


IAdminLoginService

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.ServiceModel.Web;
using System.IO;

namespace AppWcfService
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IAdminLoginService" in both code and config file together.
    [ServiceContract]
    public interface IAdminLoginService
    {
      
        [OperationContract]
        [WebInvoke(Method = "POST",
                    UriTemplate = "AdminLogin",
                    ResponseFormat = WebMessageFormat.Json,
                    BodyStyle = WebMessageBodyStyle.Bare)]
        List<GETADMINUNIQ> AdminLogin(Stream input);


        [OperationContract]
        [WebInvoke(Method = "POST",
                    UriTemplate = "FORGOTPASSWORD",
                    ResponseFormat = WebMessageFormat.Json,
                    BodyStyle = WebMessageBodyStyle.Bare)]
        MessageFormat FORGOTPASSWORD(Stream input);

    }


    [DataContract]
    public class GETADMINUNIQ
    {
        [DataMember]
        public string uniqueid 
        { get; set; }
       
    }


    [DataContract]
    public class GETADMINUNIQlist 
    {
        List<GETADMINUNIQ> _getadminli = new List<GETADMINUNIQ>();
        [DataMember]
        public List<GETADMINUNIQ> GETADMINUNIQDetailsList  
        {
            get { return _getadminli; }
            set { _getadminli = value; } 
        }
    }

  [DataContract]
    public class MessageFormat
    {      
        [DataMember]
        public string Message
        { get; set; }

    }
}

Web.Config

<?xml version="1.0"?>
<configuration>
  <appSettings>
  </appSettings> 
  <connectionStrings>
    <add name="CONNECTIONSTRING" connectionString="Data Source=192.168.1.110;User ID=sa;Password=Ecreations_123;Initial Catalog=HMS_DEV_MVC_DEMO;Integrated Security=false;Persist Security Info=True;Connect Timeout=300; pooling='true'; Max Pool Size=90;" providerName="System.Data.SqlClient"/>
  </connectionStrings>
  <system.web>
    <identity impersonate="false" />
    <httpRuntime maxRequestLength="2073741824" requestPathInvalidCharacters=""  useFullyQualifiedRedirectUrl="true" executionTimeout="14400"/>  
    <compilation debug="true" targetFramework="4.0"/>
    <authentication mode="Windows"/>
    <pages controlRenderingCompatibilityVersion="3.5" clientIDMode="AutoID"/>  
  </system.web>
  <system.webServer>
    <security>
      <requestFiltering>
        <requestLimits maxAllowedContentLength="2073741824"/>
      </requestFiltering>
    </security>
  </system.webServer>
  <system.serviceModel>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true"
      multipleSiteBindingsEnabled="true" />
    <services>
      <service behaviorConfiguration="AppWcfService.AdminLoginServiceBehavior" name="AppWcfService.AdminLoginService">
        <endpoint address="" behaviorConfiguration="web" binding="webHttpBinding" contract="AppWcfService.IAdminLoginService">
          <identity>
            <dns value="localhost"/>
          </identity>
        </endpoint>
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
      </service>
    </services>
    <behaviors>
      <endpointBehaviors>
        <behavior name="web">
          <webHttp />
        </behavior>
      </endpointBehaviors>
      <serviceBehaviors>
        <behavior name="default">
          <dataContractSerializer maxItemsInObjectGraph="2147483647" />
          <serviceMetadata httpGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="true" />
        </behavior>      
        <behavior name="AppWcfService.AdminLoginServiceBehavior">
          <serviceMetadata httpGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="false" />
        </behavior>      
      </serviceBehaviors>
    </behaviors>
    <bindings>
      <webHttpBinding>
        <binding name="RestBinding" maxReceivedMessageSize="2147483647" sendTimeout="00:10:00" maxBufferPoolSize="1073741824">
          <readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647"  maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
          <security mode="None">
          </security>
        </binding>
      </webHttpBinding>
    </bindings> 
  </system.serviceModel>
</configuration>

No comments:

Using Authorization with Swagger in ASP.NET Core

 Create Solution like below LoginModel.cs using System.ComponentModel.DataAnnotations; namespace UsingAuthorizationWithSwagger.Models {     ...