Ways Developer Can Secure An ASP.NET Application, Part 1

ASP.NET Web Services – Blast From The Past (Part 2)

Here is part 2 of this topic as promised.  It will cover consuming web service using HTTP POST and using jQuery AJAX.  If you missed part 1 of this topic, click here.

But before I start, I forgot to mention in part 1 that when you set up your web service as part of a web site, like when you deploy your web service in a virtual directory of a web site, you need to make sure the <compilation> setting in the web site’s web.config file does not have the targetFramework attribute which is usually present when targeting .NET Framework 4.0 and up.  Otherwise, your web service will not work.  Ok, so on to part 2.

 

Consuming a Web Service Using HTTP POST

Another article that covers the basics of a web service including consuming it using HTTP POST is Understanding the Basics of Web Service in ASP.NET.  I have a demo web page that uses HTTP POST to consume the simple web service I created.

Some important points:

  • When you use this method, you need to add the below config to the web service’s web.config file, otherwise you will get this error.
<configuration>
    <system.web>
		<!-- enable HttpGet and HttpPost on the web service -->
		<webservices>
			<protocols>
				<add name="HttpGet" />
				<add name="HttpPost" />
			</protocols>
		</webservices>
    </system.web>
</configuration>

 

  • The response you get will be displayed in the browser in XML format (see my demo web page).  If you want to handle the response, you need to code to send a POST request and handle the response, as in below:
protected void Translatev2Button_Click(object sender, EventArgs e)
{
	if (EnglishTextBox.Text != string.Empty)
	{
		try
		
{
	// this is the content of the request
	byte[] content = System.Text.Encoding.ASCII.GetBytes(
		"english=" + EnglishTextBox.Text);

	// create the request
	System.Net.WebRequest request = System.Net.HttpWebRequest.Create(
		"http://rodansotto.com/asmx/" +
		"TranslateToFrenchService.asmx/TranslateToFrench");
	request.Method = "POST";
	request.ContentType = "application/x-www-form-urlencoded";
	request.ContentLength = content.Length;

	// write the content to the request stream
	System.IO.Stream requestStream = request.GetRequestStream();
	requestStream.Write(content, 0, content.Length);
	requestStream.Flush(); 

	// get the response
	System.Net.WebResponse response = request.GetResponse();
	// get the stream associated with the response
	System.IO.Stream responseStream = response.GetResponseStream();
	// pipes the stream to a higher level stream reader with the 
	//  required encoding format
	System.IO.StreamReader streamReader = 
		new System.IO.StreamReader(
			responseStream, System.Text.Encoding.UTF8);

	// the response is in XML format and normally needs to be handled
	// but since the XML response is simple enough that when displayed
	//  by the browser, it only displays what we need to display,
	//  the french text
	FrenchLabel.Text = streamReader.ReadToEnd();
}
		
		catch (Exception)
		{
			throw;
		}
	}
}

 

Consuming a Web Service Using jQuery AJAX

Another way to call a web service is by using jQuery.ajax() function.  This is the preferred way by many.  Understand jQuery Ajax Function: Call Web Service Using jQuery Ajax Method shows you how.  Below is the client-side code for my demo web page that uses jQuery AJAX to consume the simple web service I created.

<head runat="server">
    
    <script src="http://ajax.googleapis.com/.../1.11.2/jquery.min.js">
    </script>
    <script>
        $(document).ready(function () {
            $("#TranslateButton").click(function () {
			
// have to add following statement to enable cross-domain request
$.support.cors = true;

$.ajax({
	type: "POST",

	url: "http://rodansotto.com/...Service.asmx/TranslateToFrench",

	//contentType: "application/x-www-form-urlencoded; charset=UTF-8",
	// no need to specify contentType above as that is the default

	data: "english=" + $("#EnglishTextBox").val(),

	dataType: "text",

	success: function (response) {
		$("#FrenchLabel").html(response);
	},

	error: function (jqXHR, textStatus, errorThrown) {
		var errorMsg = "jQuery AJAX ERROR!!!\njqXHR.statusText = " + 
			jqXHR.statusText + "\ntextStatus = " + 
			textStatus + "\nerrorThrown = " + errorThrown;
		alert(errorMsg);
	}
});
				
            });
        });
    </script>

 

Some important points:

  • If your web app will be making a cross-domain request to call the web service, you need to set $.support.cors = true, otherwise you will receive the ‘No Transport’ error.
  • And don’t forget to enable the following attribute in your web service class: [System.Web.Script.Services.ScriptService].
namespace MyWebService
{
    /// <summary>
    /// Summary description for TranslateToFrenchService
    /// </summary>
    [WebService(Namespace = "http://rodansotto.com/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script,
    //  using ASP.NET AJAX, uncomment the following line. 
    [System.Web.Script.Services.ScriptService]
    public class TranslateToFrenchService : 
        System.Web.Services.WebService
    {

 

And that concludes this topic ASP.NET Web Services – Blast From The Past.

ASP.NET Web Services – Blast From The Past (Part 1)

My last post regarding web services was June 13, 2013 and I ended it with an expectation of a sequel.  Fast forward to today, web services have now been regarded by Microsoft as legacy technologies and recommends using WCF services instead.  Then again, with Web API available why use WCF services if you are only using HTTP for these services?  That will have to be explored on a separate posts.  In this post I will revisit,  hence the title, the basics of creating a web service and the many ways of how to consume it.  I will mostly provide links to avoid reinventing the wheels but still provide my own code and demos as well.

 

Creating a Web Service and Consuming It Using WSDL Generated Proxy Class

ASP.NET – Web Services from TutorialsPoint shows you how to create a web service, how to test the web service locally, and how to consume the web service using proxy.  For this demo, I have created a simple web service and a web page that consumes it using proxy.

Some important points:

  • When creating a new project for a web service in Visual Studio 2010 and up, you need to select .NET Framework 3.5 and select the ASP.NET Web Service Application project template.  You can’t create a web service anymore starting version 4.0 of the .NET Framework.
  • Make sure to change the [WebService(Namespace = ”http://tempuri.org/”)] attribute for your web service class to something unique before you go live with your web service.  I have mine changed below:
namespace MyWebService
{
    /// <summary>
    /// Summary description for TranslateToFrenchService
    /// </summary>
    [WebService(Namespace = "http://rodansotto.com/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script,
    //  using ASP.NET AJAX, uncomment the following line. 
    //[System.Web.Script.Services.ScriptService]
    public class TranslateToFrenchService : 
        System.Web.Services.WebService
    {
        private string[,] translations =
        {
            {"good morning", "bonjour"},
            {"good evening", "bonsoir"},
            {"thank you", "merci"},
            {"please", "s'il vous plait"},
            {"welcome", "bienvenue"},
            {"goodbye", "au revoir"},
            {"see you soon", "à bientôt"}
        };

        [WebMethod]
        public string TranslateToFrench(string english)
        {
            for (int i = 0; i &lt; translations.GetLength(0); i++)
            {
                if (string.Compare(
                    english, translations[i, 0], true) == 0)
                {
                    return translations[i, 1];
                }
            }
            return "";
        }
    }
}

 

  • There are also other ways of consuming a web service besides using proxy.  You have HTTP POST method and XMLHTTP.  I will show how to use HTTP POST method later in this post.  As for XMLHTTP, you use the XMLHTTPRequest object in JavaScript.  It’s a lot of work setting this up and the following articles show you how: Calling a Web Service from Javascript using XMLHttpRequest and Consuming .NET Web Services using XMLHTTP protocol.  An alternative way is to use ASP.NET AJAX and Consuming a Web Service using ASP.NET Ajax shows you how.  But a better way is to use jQuery AJAX which I will also show how later in this post.
  • When calling a web service using proxy, you will need to add a web reference.  In Visual Studio 2010 and up, you have the option to add it as a service reference.  In fact Visual Studio is recommending you add it as a service reference rather than a web reference because web reference is using the legacy .NET Framework 2.0 web services technology and is there only for compatibility reason.
    • Add as a service reference.  Walkthrough: Creating and Accessing WCF Services from MSDN shows you how to add a service reference.  When you add a service reference, additional config is added to the consuming app’s web.config file under <configuration>.  The following is the config that was added to my web page’s site’s web.config file:
    <configuration>
    	<!-- config added for using a service reference -->
    	<system.serviceModel>
    		<bindings>
    			<basicHttpBinding>
    				<binding name="TranslateToFrenchServiceSoap"/>
    			</basicHttpBinding>
    		</bindings>
    		<client>
    			<endpoint 
    			address=
    		"http://rodansotto.com/asmx/TranslateToFrenchService.asmx"
    			binding="basicHttpBinding"
    			bindingConfiguration="TranslateToFrenchServiceSoap"
    			contract="MyWebServiceB.TranslateToFrenchServiceSoap"
    			name="TranslateToFrenchServiceSoap"/>
    		</client>
    	</system.serviceModel>
    </configuration>
    

     

    To invoke the web service method using the service reference, I used the following code where MyWebServiceB is the namespace I provided:

    protected void Translatev2Button_Click(object sender, EventArgs e)
    {
    	if (Englishv2TextBox.Text != string.Empty)
    	{
    		try
    
    {
    	// consuming a web service using a service reference
    	MyWebServiceB.TranslateToFrenchServiceSoapClient soapClient = 
    		new MyWebServiceB.TranslateToFrenchServiceSoapClient();
    	Frenchv2Label.Text = 
    		soapClient.TranslateToFrench(Englishv2TextBox.Text);
    }
    
    		catch (Exception)
    		{
    			throw;
    		}
    	}
    }
    

     

    • Add as a web reference.  To add a web reference you have to go to the same Add Service Reference dialog window and click the Advanced… button.  Then click the Add Web Reference… button.  The following are the config added to my web page’s site’s web.config file and also the code I used to invoke the web service method.  You will see the differences between adding as a web reference and adding as a service reference.
<configuration>
	<!-- config added for using a web reference -->
	<applicationsettings>
		<mywebapp.properties.settings>
			<setting 
			name="MyWebApp_MyWebService_TranslateToFrenchService" 
			serializeas="String">
				<value>
			http://rodansotto.com/asmx/TranslateToFrenchService.asmx
				</value>
			</setting>
		</mywebapp.properties.settings>
	</applicationsettings>
</configuration>

 

protected void TranslateButton_Click(object sender, EventArgs e)
{
	if (EnglishTextBox.Text != string.Empty)
	{
		try
		{
			// consuming a web service using a web reference
			MyWebService.TranslateToFrenchService service = 
				new MyWebService.TranslateToFrenchService();
			FrenchLabel.Text = 
				service.TranslateToFrench(EnglishTextBox.Text);
		}
		catch (Exception)
		{
			throw;
		}
	}
}

 

Ok so that’s how you consume a web service using proxy.  This post has turned out to be longer than I expected so I decided to break this down into multiple parts, thus part 1 of this post ends here.  I will continue with consuming a web service using HTTP POST method on part 2.

ASP.NET: What are web services?

  • Web services are services provided over the web using standard technologies such as XML, a W3C standard.
  • Any application on any platform can consume a web service as long as it is able to understand XML.
  • XML is text based, thus it is quick and easy to download and even easier to use.
  • To consume an ASP.NET web service, look for an .asmx file.
  • An example of a web service is http://www.webservicex.net/ConvertTemperature.asmx.
  • There are 3 methods used to communicate with a web service: HTTP-GET, HTTP-POST, and SOAP.
  • In HTTP GET and POST, the response body is an XML.  Below is an example response from the ConvertTemperature web service mentioned above, converting 21.5 degrees Celcius to degrees Farenheit.
    <?xml version="1.0" encoding="UTF-8"?>
    <double xmlns="http://www.webserviceX.NET/">70.7</double>

     

 

  • SOAP (Simple Object Access Protocol) is basically a well-formed XML created just for the purpose of sending requests and receiving responses to and from the web service.
  • A SOAP request is wrapped in an HTTP-POST.  The example below is the SOAP request sent to the ConvertTemperature web service, separated into a request header and request body:
    POST /ConvertTemperature.asmx HTTP/1.1
    Host: www.webservicex.net
    Content-Type: text/xml; charset=utf-8
    Content-Length: [length]
    SOAPAction: "http://www.webserviceX.NET/ConvertTemp"

     

    <?xml version="1.0" encoding="utf-8"?>
    <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
      <soap:Body>
        <ConvertTemp xmlns="http://www.webserviceX.NET/">
          <Temperature>21.5</Temperature>
          <FromUnit>degreeCelsius</FromUnit>
          <ToUnit>degreeFahrenheit</ToUnit>
        </ConvertTemp>
      </soap:Body>
    </soap:Envelope>

     

 

  • The corresponding SOAP response is below (response header not shown):
    <?xml version="1.0" encoding="utf-8"?>
    <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
      <soap:Body>
        <ConvertTempResponse xmlns="http://www.webserviceX.NET/">
          <ConvertTempResult>70.7</ConvertTempResult>
        </ConvertTempResponse>
      </soap:Body>
    </soap:Envelope>

     

 

  • In the SOAP request and response body, you need to have at the minimum the SOAP tags <Envelope> and <Body>.  You can also have the optional SOAP tag <Header>.  Inside the <Body> SOAP tag contains other tags that are specific to the web service.

 

In my next post, I will talk about what is required to create a web service in ASP.NET.

ASP.NET: GET, POST, IsPostBack, QueryString, and Form

I have been asked a couple of times in my job interviews about GET, POST, IsPostBack, QueryString, and Forms.  These are the basics that one who has worked on ASP.NET should know.  Sometimes you get focused on higher level stuff especially if you are working with wrappers or some sort of framework on top of ASP.NET that you lose focus on the basics.  It happens.  At least to me it happens.

So what is GETGET is one of the most common HTTP commands, just like POST, that is sent by the browser to the web server.  It tells the web server to get or fetch a page for the browser.  So when you type a URL

 

on your browser’s address window and press ENTER, the browser sends a GET command to the web server and the web server fetches the page and sends it back to the browser and the browser displays the page.  Simple.

POST, on the other hand, is sent by the browser to the web server if it needs to post or send back data or information to the web server.  So when you fill up information on a web page, say maybe you are creating a new user account, and pressed a submit button, the browser sends a POST command, attaches the information you entered and sends it to the web server.

IsPostBack is a property of the Page class representing a Web Forms page in ASP.NET.  You use this property to check if the page is being loaded or rendered or being requested for the first time (a GET command) as opposed to being loaded as a response to a postback (a POST command).

Querystring is the string you see in a URL after the ? character

 

It allows you to pass data from one page to another.  It can contain more than one name/value pair

form=MSHOME
setlang=en
q=asp.net

 

separated by the & character.  On the target page (e.g. results.aspx) one can access the name/value pair using the QueryString collection of the Request object

Request.QueryString("form");
Request.QueryString("setlang");
Request.QueryString("q");

 

Form collection is another property of the Request object that allows you to access the information sent by the browser through a POST command.  It retrieves the values of the form elements.  So if we have the following form tag:

<form method="POST" action = "getCustomer.aspx" >
    Enter Customer ID:
    <input type="text" name="Id">
    <input type="submit" value="Get Customer">
</form>

 

we can retrieve the customer ID using the following code:

Request.Form("Id");