简体   繁体   中英

How to set cookie when winform application calls service

I have an asp.net web service and a winforms app. The winform application calls the methods of the web service.

my code in asp.net web service asmx page:

namespace ServicesTinhLuong
{
    public class ServicesTinhLuong : System.Web.Services.WebService
    {
        #region Login Webservice
        [WebMethod(Description = "Login Webservice")]

        public bool LogIn(string username, string password)
        {
            try
            {
                var usernameCF = WebConfigurationManager.AppSettings["LogInServiceUser"];
                var passCF = WebConfigurationManager.AppSettings["LogInServicePass"];
                passCF = new Common().EncPwd(passCF);
                var loginSuccess = (username == usernameCF) && (password == passCF);
                if (loginSuccess)
                {
                    FormsAuthentication.SetAuthCookie(username, true);
                    return true;
                }
                return false;
            }
            catch (Exception ex)
            {
                return false;
            }
        }

        [WebMethod(Description = "Logout Webservice")]
        [PrincipalPermission(SecurityAction.Demand, Authenticated = true)]
        public bool LogOut()
        {
            if (HttpContext.Current.User.Identity.IsAuthenticated)
                FormsAuthentication.SignOut();
            return true;
        }
        #endregion
        [WebMethod]
        [PrincipalPermission(SecurityAction.Demand, Authenticated = true)]
        public bool checkLogin(string username, string password)
        {
            try
            {
                SqlCommand command = new SqlCommand("CheckLogin", connection)
                {
                    CommandType = CommandType.StoredProcedure
                };
                command.Parameters.AddWithValue("@UserName", username);
                command.Parameters.AddWithValue("@Pass", password);

                if (connection.State == ConnectionState.Closed) connection.Open();
                DataTable dt = new DataTable();
                using (SqlDataAdapter adapter = new SqlDataAdapter(command))
                {
                    adapter.Fill(dt);
                    command.Dispose();
                }
                connection.Close();
                if (dt.Rows.Count > 0) return true;
                else return false;
            }
            catch (Exception ex)
            {
                return false;
            }
            }
      }
}

web.config

<configuration>
  <connectionStrings>
    <add name="ServerName" connectionString="DUONG-PC" />
    <add name="DatabaseName" connectionString="TinhLuong" />
    <add name="UserID" connectionString="sa" />
    <add name="Password" connectionString="sa123" />
  </connectionStrings>
  <appSettings>
    <add key="LuongCoBan" value="1120000" />
    <add key="LogInServiceUser" value="duonglb" />
    <add key="LogInServicePass" value="79958" />
  </appSettings>
  <system.web>
    <authentication mode="Forms">
      <forms name="AuthCookie" path="/" cookieless="UseCookies"></forms>
    </authentication>
    <compilation debug="true" targetFramework="4.5"/>
    <httpRuntime targetFramework="4.5"/>
    <httpModules>
      <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web"/>
    </httpModules>
  </system.web>
  <system.codedom>
    <compilers>
      <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701"/>
      <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 /define:_MYTYPE=\&quot;Web\&quot; /optionInfer+"/>
    </compilers>
  </system.codedom>
  <system.webServer>
    <validation validateIntegratedModeConfiguration="false"/>
    <modules>
      <remove name="ApplicationInsightsWebTracking"/>
      <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" preCondition="managedHandler"/>
    </modules>
  </system.webServer>
</configuration>

I add Service References in winforms app:

public ServicesTinhLuong.ServicesTinhLuongSoapClient service = new ServicesTinhLuong.ServicesTinhLuongSoapClient();

scenario: when the application WinForms call web service methods will have to log in through the login method (string username, string password), after successful login web service to store cookies. then WinForms app can call other methods of web services without logging in again through the login method

for authentication in web service there is so many ways using behaviors and else .... but there is some links whit samples will help you

https://www.codeproject.com/Articles/9348/Web-Service-Authentication

https://www.codeproject.com/Articles/4398/Authentication-for-Web-Services-using-SOAP-headers

I suggest you seccend link

if your session die user need login


again

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM