Search code examples
c#asp.netwcfwcf-rest

Consuming WCF Rest 4 From ASP . NET


I am a complete ASP .NET newbie. I've written a set of web services using the WCF 4 Rest Starter Kit. I call everything from within a Flash application but I want to write a quick and dirty admin panel for myself to use which has no need to be written in Flash.

I figure it will be faster to get this up and running in ASP. So the question is consider a WCF function like this:

[WebInvoke(UriTemplate = "/Login/", Method = "POST")]
        public User Login(User user)
        {
             // Code here
             // Either throw a WebFaultException or return the logged in user with a session id

How would I consume this from an ASP .Net page with a username, password, submit box and it either displays errors 401's etc or success (returneduser.sessionid).

Thanks!

Note: I am aware of how to call a Rest service over Http in C#. It's really a question of is there a "nice way" to due this in ASP or is it just make a form like:

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<form action="WebForm2.aspx.cs" >
    <asp:textbox id="Email" runat="server"/>
    <asp:textbox id="Password" runat="server"/>
    <asp:Button id="Button1" OnClick="OnButtonClick" runat="server" Text="Login"/>
  </form>
  <asp:Label ID="labelResult" runat="server" />
</asp:Content>

Then on click in the code behind do something like this:

 protected  void OnButtonClick(object sender, EventArgs e)
        {
            HttpWebRequest req = WebRequest.Create("http://localhost:35810/Users/Login/") as HttpWebRequest;

            String userString = UsefulStuff.Serialization.SerializationUtil.
                SerializeDataContractToString(typeof(User), new User() { Email =  new Email(textboxUsername.text),
                                                                         Password = new Password(textboxPassword.text) });

            String strResponse = GetHttpPostResponse(req, userString);

            User recievedUser = UsefulStuff.Serialization.SerializationUtil.DeserializeDataContractString(
                typeof(User), strResponse) as User;

            labelResult.Text = recievedUser.SessionId;
        }


        public static String GetHttpPostResponse(HttpWebRequest httpWebRequest, String serializedPayload)
        {
            httpWebRequest.Method = "POST";
            httpWebRequest.ContentType = "text/xml";
            httpWebRequest.ContentLength = serializedPayload.Length;

            StreamWriter streamOut = new StreamWriter(httpWebRequest.GetRequestStream(), Encoding.ASCII);
            streamOut.Write(serializedPayload);
            streamOut.Close();

            StreamReader streamIn = new StreamReader(httpWebRequest.GetResponse().GetResponseStream());

            string strResponse = streamIn.ReadToEnd();
            streamIn.Close();

            return strResponse;
        }

Solution

  • Basic approach to call REST service is by HttpWebRequest

    // User object serialized to XML
    XElement data = new XElement("User",
      new XElement("UserName", UserName),
      new XElement("Password", Password)
    );
    
    MemoryStream dataSream = new MemoryStream();
    data.Save(dataStream);
    
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(YourServiceUrl);
    request.Method = "POST";
    request.ContentType = "application/xml";
    // You need to know length and it has to be set before you access request stream
    request.ContentLength = dataStream.Length; 
    
    using (Stream requestStream = request.GetRequestStream())
    {
      dataStream.CopyTo(requestStream);   
      requestStream.Close();
    } 
    
    HttpWebResponse response = request.GetResponse();
    if (response.Status == HttpStatusCode.Unauthorized)
    {
      ...
    }
    else
    {
      ...
    }
    response.Close();