How can you change the default ContentType in ServiceStack?

試著忘記壹切 提交于 2019-12-19 10:27:57

问题


I have registered a new content type in ServiceStack with:

appHost.ContentTypeFilters.Register("application/x-my-content-type", 
   SerializeToStream, DeserializeFromStream);

And everything works as expected, if the client sends the content type in the http stream.

Unfortunately, I have a client that is not in my control of HTTP Request Heads and does not send the content type.

How can I get ServiceStack to set the default content type for that route?


回答1:


On every ServiceStack /metadata page lists the different ways a client can request a specific Content-Type:

To override the Content-type in your clients HTTP Accept Header, append ?format=xml or add .format extension

E.g. The client can specify your custom ContentType with ?format=x-my-content-type, adding .x-my-content-type extension or by specifying the HTTP Header (in the HttpClient):

Accept: application/x-my-content-type

Otherwise if your HttpClient doesn't send an Accept header you can specify the default content type in your AppHost with:

SetConfig(new HostConfig {
     DefaultContentType = "application/x-my-content-type"
});

Note: All Configuration options in ServiceStack are set on HostConfig.

The issue when calling web services from a web browser is that they typically ask for Accept: text/html which by contract ServiceStack obliges by returning back HTML if it is enabled.

To ensure your Content-Type is always returned you may also want to disable the HTML feature with:

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

Otherwise if you want to override the Accept header you can force your service to always return your Content-Type by decorating your Response DTO inside a HttpResult, i.e:

return new HttpResult(dto, "application/x-my-content-type");

Otherwise anywhere outside of your Service (e.g. Request/Response filter) you can set the Response ContentType anywhere that has access to a IHttpRequest with:

httpReq.ResponseContentType = "application/x-my-content-type";


来源:https://stackoverflow.com/questions/12326810/how-can-you-change-the-default-contenttype-in-servicestack

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!