当使用ColdFusion 10的新REST API时,我如何管道进入响应管道,以便在ColdFusion 10的REST API序列化之后我可以更改JSON响应?
例如,假设我有以下终点:
<cfcomponent rest="true" restpath="/widgets" produces="application/json">
<cffunction name="getWidget" access="remote" httpmethod="GET" restpath="{id}" returntype="struct">
<cfargument name="id" required="true" restargsource="path" type="numeric"/>
<cfreturn {
id = arguments.id,
code = "string:.10"
} />
</cffunction>
</cfcomponent>
此方法返回后(即在ColdFusion使用SerializeJSON创建JSON响应之后),我想用空字符串替换“string:”。我尝试这样做(使用此处描述的技术:http://house-of-fusion.10909.n7.nabble.com/getPageContext-in-onRequestEnd-is-empty-td78578.html)但我无法更改响应。有谁知道如何改变回应?
背景
我之所以要寻找这样的黑客,是因为SerializeJSON(CF 10 REST API使用的默认序列化)会将 code =“。10”视为浮动并呈现“代码”:0.1 ,这不是我想要的。这个问题已有详细记录,但是在使用本机REST API时解决此问题的解决方案似乎没有在任何地方记录。
答案 0 :(得分:1)
似乎没有办法利用ColdFusion的响应管道来编辑ColdFusion 10的REST API生成的响应体。但是,对于IIS用户,可以使用HttpModules。你需要在.NET中编写HttpModule,但它非常简单。我写了几个HttpModule来处理ColdFusion的响应,源代码可以在这里找到:
https://github.com/johnnyoshika/coldfusion-rest-post-process
如果您正在尝试解决我在此问题中发现的相同问题,您可以使用我在此处发布的HttpModule:
https://github.com/johnnyoshika/coldfusion-rest-post-process/blob/master/JsonStringCleanserModule.cs
要将其插入您的应用程序,您可以按照以下步骤操作:
1)抓住准备使用的DLL:
https://github.com/johnnyoshika/coldfusion-rest-post-process/tree/master/bin/Release
从该URL抓取ColdFusion.RestPostProcess.dll
文件并将其放入ColdFusion应用程序的bin文件夹中
例如,如果您的ColdFusion应用程序在此处:
C:/myapp
然后你想把dll放在这里:
C:/myapp/bin/ColdFusion.RestPostProcess.dll
如果您不想信任陌生人的DLL,则需要查看源代码并自行在Visual Studio中编译项目以生成DLL。
2)修改web.config
修改或创建应用程序根目录中的web.config文件。内容应如下所示:
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.web>
<httpModules>
<!-- This is for IIS5, IIS6, and IIS7 Classic -->
<add name="JsonStringCleanserModule" type="ColdFusion.RestPostProcess.JsonStringCleanserModule"/>
</httpModules>
</system.web>
<system.webServer>
<modules>
<!-- This is for IIS7+ Integrated mode -->
<add name="JsonStringCleanserModule" type="ColdFusion.RestPostProcess.JsonStringCleanserModule"/>
</modules>
</system.webServer>
</configuration>
** 3)在***string***:
每当您想要在JSON中输出字符串时,请在***string***:
之前添加值。例如:
<cffunction name="getWidget" access="remote" httpmethod="GET" restpath="{id}" returntype="struct">
<cfargument name="id" required="true" restargsource="path" type="numeric"/>
<cfreturn {
id = arguments.id,
code = "***string***:.10"
} />
</cffunction>
应该这样做。添加***string***:
强制ColdFusion将值序列化为字符串,然后HttpModule将删除***string***:
的所有实例,以便最终输出为:
{"id":1,"code":".10"}
答案 1 :(得分:0)
您还可以使用here
描述的自定义响应您自己将数据序列化为json,更改字符串并将其设置为响应内容。简而言之,函数内部的代码如下所示:
<cfset response=structNew()>
<cfset response.status=201>
<cfset var content = SerializeJSON(data)>
<!--- change the content string --->
<cfset response.content= content>
<cfset response.headers=structNew()>
<cfset restSetResponse( response )>
HTH。