ServiceStack - 关闭快照

jov*_*a85 3 snapshot servicestack

我在这里遵循了如何创建ServiceStack的说明:

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

我确信我已经跟着它去了,但是一旦我运行Web应用程序.我得到了一个关于我的回复的"快照"视图.我知道当我没有默认视图/网页时会发生这种情况.我将项目设置为ASP.net网站,而不是ASP.net MVC网站.这可能是问题吗?

快照

我还用以下C#代码编写了一个测试控制台应用程序.它将响应作为HTML网页而不是简单的字符串,例如"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);
        }
Run Code Online (Sandbox Code Playgroud)

如何关闭"快照"视图?我究竟做错了什么?

Wil*_*ith 6

浏览器正在请求html,因此ServiceStack正在返回html快照.

有两种方法可以停止快照视图:

  • 首先是使用servicestack提供的ServiceClient类.这些还具有自动路由和强类型响应DTO的优点.
  • 接下来的方法是Accept将请求的头部设置为类似的application/json或者application/xml将响应序列化为json或xml.这就是ServiceClients在内部所做的事情
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
    request.Accept = "application/json";
    ...
  • 另一种方法是添加一个调用的查询字符串参数format并将其设置为jsonxml
    string url = "http://localhost:51450/hello/?format=json";