问题描述
我正在使用 ColdFusion 10 的新内置 REST API,我想返回状态代码 201(已创建).我首先尝试了此处描述的 RestSetResponse() 方法:http:///www.adobe.com/devnet/coldfusion/articles/restful-web-services.html.它运行良好,除了它强制您将函数的返回类型设置为void".void"的问题在于,每当我抛出异常时,它就不再返回正确的 JSON 错误消息.
I'm using ColdFusion 10's new built-in REST API and I'd like to return a status code of 201 (Created). I first tried the RestSetResponse() approach that's described here: http://www.adobe.com/devnet/coldfusion/articles/restful-web-services.html. It works well, except that it forces you to set the function's returntype to "void". The problem with "void" is that whenever I throw an exception, it no longer returns the proper JSON error message.
抛出这个异常:
<cfthrow errorcode="400" message="Validation error." />
当返回类型为struct"时,返回格式良好的 JSON:
Returns a nicely formatted JSON when the returntype is "struct":
HTTP/1.1 400 Bad Request
Content-Type: application/json
{"Message":"Validation error."}
但是当返回类型为void"时(这是使用 RestSetResponse() 所必需的),响应是一些丑陋的 HTML 响应.
But when the returntype is "void" (which is required to use RestSetResponse(), the response is some ugly HTML response.
因此,我不得不恢复使用返回类型struct",放弃了 RestSetResponse(),并尝试了这个:
Because of this, I had to revert to using returntype "struct", gave up on RestSetResponse(), and tried this:
<cfheader statusCode="201" statusText="Created" />
但它不起作用.似乎 ColdFusion 会覆盖 statusCode 并在成功时始终返回 200(OK).任何人都知道在不将函数的返回类型设置为void"的情况下将状态码更改为 201 的方法吗?
But it doesn't work. It seems that ColdFusion overwrites the statusCode and always returns 200 (OK) when it's successful. Anyone know of a way to change the status code to 201 without setting the returntype of the function to "void"?
推荐答案
我看不出为什么 restSetResponse()
应该要求返回类型为 void,但已经证实如果不是这种情况.这有点垃圾.
I can't see a good reason why restSetResponse()
should require a returntype of void, but have verified it is ignored if this is not the case. Which is a bit rubbish.
通过解决您的情况,我唯一能想到的就是滚动您自己的结构,其中包含错误详细信息,然后将其用作 content
为 设置的值>restSetResponse()
调用.
The only thing I can think by way of working around your situation is to roll-your-own struct with the error detail in it, then use that as the content
value set for the restSetResponse()
call.
我认为这有点临时工,但在这种情况下,您会受到 ColdFusion 临时工的限制.
This is a bit jerry-built, but you're constrainted by the jerry-built-ness of ColdFusion in this instance, I think.
这篇关于ColdFusion 10 REST API:如何在没有 RestSetResponse() 的情况下设置状态代码 201的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!