How to create asmx web service using username and password as a credentials?

2.3k Views Asked by At

I want to create webservice take username and password as a crediantials

My class is

public class UserDetails : System.Web.Services.Protocols.SoapHeader
    {
        public string userName { get; set; }
        public string password { get; set; }
       public bool IsValid()
        {
            //Write the logic to Check the User Details From DataBase  
            //i can chek with some hardcode details UserName=Nitin and Password=Pandit  
            return this.userName == "xxxxx" && this.password == "xxxxxxx";
            //it'll check the details and will return true or false   
        }

my asmx file is

public UserDetails User;
        [WebMethod]
        [SoapHeader("User", Required = true)]
        public void SayHello(string userName)
        {
            if (User != null)
            {
                if (User.IsValid())
                {
                    Context.Response.ContentType = "application/json; charset=utf-8";
                    Context.Response.Write("Hello... " + userName + "");
                }
                else
                {
                    Context.Response.ContentType = "application/json; charset=utf-8";
                    Context.Response.Write("user crediantials not valid");
                }
            }
            else
            {
                Context.Response.ContentType = "application/json; charset=utf-8";
                Context.Response.Write("Error in authentication");
            }
        }

when ever iam calling service doesnot taking crediatials going into else condition. iam calling service like this shown below but iam getting error response.

HttpWebRequest request = HttpWebRequest.Create(Url.weburl + "SayHello?userName=pavan") as HttpWebRequest;
               // String encoded = System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(username + ":" + password));
                request.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.GetEncoding("ISO-8859-1").GetBytes(username + ":" + password));
                //  request.Credentials = new NetworkCredential("reload", "reload123");
                request.Method = "GET";





                WebResponse response = await request.GetResponseAsync();
            using (var reader = new StreamReader(response.GetResponseStream()))
            {
                result = reader.ReadToEnd();

}

whenever I am calling service user value always null.how to pass credentials.please help me. I am searching this from last 2 days.still not getting solutions,please help me.

0

There are 0 best solutions below