views:

250

answers:

4

I need to create a simple webservice in C# but I'm not sure where to start (I've coded UI apps in C# before but all my web experience is in Ruby on Rails). Where do I start?

The only client for the webservice will be a Ruby on Rails app so there's no need for any HTML rendering. I was thinking of just returning a XML or YAML formatted string unless there's an easier way. I'm not too keen on SOAP but if it's easy/natural in C# & Ruby then I'd consider it (or anything else).

A: 

here is a simple example.

I used Visual Studio to create a .asmx file and put this in the .cs code behind.

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Services;
using System.Web.Script.Services;

namespace MyNamespace.Newstuff.Webservice
{
    [WebService(Namespace = "http://iamsocool.com/MyNamespace/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    [ScriptService]
    public class MyNamespace : System.Web.Services.WebService
    {
        [WebMethod]
        public string HelloWorld()
        {
            return "Hello World";
        }
    }
}
Mark Schultheiss
+1  A: 

If you have an IIS 6 or 7 environment you can deploy to, I would just create an ASP.NET-MVC 2 application. You can create one with the Visual Studio template and then have a controller like this:

public class ApiController : Controller {        

        public ActionResult Index(string id) {

            var xml = new XElement("results", 
                            new XAttribute("myId", id ?? "null"));

            return Content(xml.ToString(), "text/xml");
        }

    }

The output of a URL like http://localhost:4978/Api/Index/test is:

<results myId="test"/>

You could easily extend this to return whatever format you want (JSON, etc). In any case, ASP.NET MVC makes it pretty easy to create a REST API, which should be easy to consume from Ruby.

+1  A: 

If you want the flexibility of WCF, the following code should get you started. WCF can be more complicated than the other answers, but it provides some benefits like increased flexibility and being able to host your services from a Windows Service.

Create a service that looks like:

    [ServiceContract]
    public interface ITestService {

        [OperationContract]
        [WebGet(
            BodyStyle = WebMessageBodyStyle.Bare,
            ResponseFormat = WebMessageFormat.Xml            
            )]
        XElement DoWork(string myId);

    }

And the implentation would be:

    public class TestService : ITestService {

        public XElement DoWork(string myId) {

            return new XElement("results", new XAttribute("myId", myId ?? ""));
        }
    }

Your application config (web.config or app.config) file would contain something like the following:

    <system.serviceModel>
        <behaviors>
      <endpointBehaviors>
        <behavior name="WebBehavior">
          <webHttp />          
        </behavior>
      </endpointBehaviors>
    </behaviors>
        <services>
            <service name="WebApplication1.TestService">
                <endpoint behaviorConfiguration="WebBehavior"
                  binding="webHttpBinding" 
                  contract="WebApplication1.ITestService">
                </endpoint>             
            </service>
        </services>
    </system.serviceModel>

If you were to host this on an ASP.NET site, you'd have a file called TestService.svc with the following in it:

<%@ ServiceHost Language="C#" Debug="true" 
                Service="WebApplication1.TestService" 
                CodeBehind="TestService.svc.cs" %>
I actually went for something like this in the end.. but switched to JSON formatting. I used this blog post as a reference: http://dotnetninja.wordpress.com/2008/05/02/rest-service-with-wcf-and-json/
hopeless
A: 

I agree with the MVC route. Here is what I use to kick objects out as XML:

public class XmlResult : ActionResult {
    public XmlResult(object anObject) {
        Object = anObject;
    }

    public object Object { get; set; }

    public override void ExecuteResult(ControllerContext aContext) {
        if (aContext == null) throw new Exception("Context cannot be null");
        var response = aContext.HttpContext.Response;
        response.ContentType = "application/xml";
        SerializeObjectOn(Object, response.OutputStream);
    }

    private void SerializeObjectOn(object anObject, Stream aStream) {
        var serializer = new XmlSerializer(anObject.GetType());
        serializer.Serialize(aStream, anObject);
    }
}

public class MyController : Controller {
    public ActionResult Index() {
        return  new XmlResult(object);
    }
}

Request it through http://localhost/mycontroller

Hupperware