IamCalvinBrown.com a Blog Site

Code Examples, Consulting Advice and lots of other cool things

WCF - Return JSON Content (for Angular consumption)


Note: If you use string as a return type, it will not work when consumed directly by Angular.

You need 3 pieces:

  1. WCF Service (ex: RestService.svc)
  2. WCF Interface Class (ex: IRestService.cs)
  3. Newtonsoft.Json (install this package)
What the interface should look like:
public interface IRestService
{
     [OperationContract]
      void getContentInJsonFormat(string id);
}

What the WCF Service looks like:
public class RestService: IRestService
{
     [WebGet(ResponseFormat = WebMessageFormat.Json, BodyStyle =WebMessageBodyStyle.Bare)]
    public void getContentInJsonFormat(string id)
    {
          string workingString = "some random text or object";  // you should actually put a Json string here or create a class to return

         HttpContext.Current.Response.ContentType = "application/json; charset=utf-8";
         HttpContext.Current.Response.Write("[" + JsonConvert.SerializeObject(workingString) + "]");
    }
}

How to call this service:
(when hosted) http://www.IamCalvinBrown.com/restservice/IamCalvinBrown/123
(locally) http://localhost:3242/RestService.svc/IamCalvinBrown/123

The url is unique to your website, so please don't use port 20949 unless it's actually your sites port. RestService is the name of the WCF service. 123 is the input parameter.

Happy coding.

Loading