ServiceStack default format

前端 未结 3 1183
臣服心动
臣服心动 2020-12-15 05:22

I would like to set ServiceStack\'s default format to JSON, as opposed to the HTML formatted response it normally returns when a service is accessed from a browser. I know

3条回答
  •  甜味超标
    2020-12-15 05:58

    Late to the question, but since I couldn't find the answer anywhere, I finally figured it out from ServiceStack's source code :)

    The simplest way I found to default to Json instead of Html from the browser was this:

    HttpRequestExtensions.PreferredContentTypes = new[] { MimeTypes.Json, MimeTypes.Xml };
    

    Call this at the startup of your app, and it will override default's ServiceStack mime types and start with json (which will work with your browser's requests since / will match it).

    Note that you should still disable Html and make Json the default mime type:

    SetConfig(new HostConfig {
         DefaultContentType = MimeTypes.Json 
         EnableFeatures = Feature.All.Remove(Feature.Html),
    });
    

    For the curious: ServiceStack uses internally HttpRequestExtensions.GetResponseContentType (see HttpRequestExtensions.cs), which loops through preferred content types. Because it contains MimeTypes.Html, it will catch the first accept type from the browser (text/html) and ignore whatever is coming after. By overriding this, text/html is not seen as a preferred content type, and it then skips to */* which defaults to json as expected.

提交回复
热议问题