Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ServiceStack - Switch off Snapshot

I've followed instructions on how creating a ServiceStack here at:

https://github.com/ServiceStack/ServiceStack/wiki/Create-your-first-webservice

I'm sure I have followed it to the letter, but as soon as I run the web application. I get a 'Snapshot' view of my response. I understand this happens when I don't have a default view/webpage. I set up the project as a ASP.net website, not a ASP.net MVC website. Could that be the problem?

Snapshot

I also wrote a test console application with the following C# code. It got the response as a HTML webpage rather than as a plain string e.g. "Hello, John".

static void sendHello()
        {
            string contents = "john";
            string url = "http://localhost:51450/hello/";

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "POST";
            request.ContentLength = contents.Length;
            request.ContentType = "application/x-www-form-urlencoded";

            // SEND TO WEBSERVICE
            using (StreamWriter writer = new StreamWriter(request.GetRequestStream()))
            {
                writer.Write(contents);
            }

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            string result = string.Empty;

            using (StreamReader reader = new StreamReader(response.GetResponseStream()))
            {
                result = reader.ReadToEnd();
            }

            Console.WriteLine(result);
        }

How can I switch off the 'snapshot' view? What am I doing wrong?

like image 662
jova85 Avatar asked Sep 06 '13 08:09

jova85


2 Answers

The browser is requesting html so ServiceStack is returning the html snapshot.

There are a couple of ways to stop the snapshot view:

  • First is to use the ServiceClient classes provided by servicestack. These also have the advantage of doing automatic routing and strongly typing the response DTOs.
  • Next way would be to set the Accept header of the request to something like application/json or application/xml which would serialize the response into json or xml respectively. This is what the ServiceClients do internally
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
    request.Accept = "application/json";
    ...
  • Another method would be to add a query string parameter called format and set it to json or xml
    string url = "http://localhost:51450/hello/?format=json";
like image 149
Will Smith Avatar answered Oct 01 '22 19:10

Will Smith


Putting the specific format requesting is the practical way to do this

string url = "http://localhost:51450/hello/?format=json";
like image 33
Axel Paco Avatar answered Oct 01 '22 20:10

Axel Paco