ColdFusion 10 REST API: How to set status code 201 without RestSetResponse()

感情迁移 提交于 2019-12-10 04:21:08

问题


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.

Throwing this exception:

<cfthrow errorcode="400" message="Validation error." />

Returns a nicely formatted JSON when the returntype is "struct":

HTTP/1.1 400 Bad Request
Content-Type: application/json

{"Message":"Validation error."}

But when the returntype is "void" (which is required to use RestSetResponse(), the response is some ugly HTML response.

Because of this, I had to revert to using returntype "struct", gave up on RestSetResponse(), and tried this:

<cfheader statusCode="201" statusText="Created" />

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"?


回答1:


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.

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.

This is a bit jerry-built, but you're constrainted by the jerry-built-ness of ColdFusion in this instance, I think.

I've logged a bug relating to this.



来源:https://stackoverflow.com/questions/15711287/coldfusion-10-rest-api-how-to-set-status-code-201-without-restsetresponse

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