【问题标题】:ServiceStack - Switch off SnapshotServiceStack - 关闭快照
【发布时间】:2026-02-05 21:25:01
【问题描述】:

我已按照说明在此处创建 ServiceStack:

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

我确信我已经完全按照它的要求进行操作,但只要我运行 Web 应用程序。我得到了我的回复的“快照”视图。我了解当我没有默认视图/网页时会发生这种情况。我将项目设置为 ASP.net 网站,而不是 ASP.net MVC 网站。会不会是这个问题?

我还使用以下 C# 代码编写了一个测试控制台应用程序。它以 HTML 网页而不是纯字符串的形式获得响应,例如“你好,约翰”。

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);
        }

如何关闭“快照”视图?我做错了什么?

【问题讨论】:

    标签: servicestack snapshot


    【解决方案1】:

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

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

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

    【讨论】:

    • 这是我必须设置的接受。我不敢相信我错过了。谢谢!
    【解决方案2】:

    提出具体的格式请求是这样做的实用方法

    string url = "http://localhost:51450/hello/?format=json";
    

    【讨论】:

      【解决方案3】:

      我建议直接删除此功能。

      public override void Configure(Container container)
      {
          //...
          this.Plugins.RemoveAll(p => p is ServiceStack.Formats.HtmlFormat);
          //...
      }
      

      现在所有带有 Content-Type=text/html 的请求都将被忽略。

      【讨论】: