request.format returns * / * [英] request.format returning */*
问题描述
我目前正在为RoR上的应用程序开发API
I'm currently developing an API for my application on RoR
例如,我创建了一些XML,加载了创建对象所需的所有信息,让我们说一个Person,并使用Curl我将它提交到我的应用程序
As an example, I created some XML, loaded with all the info I need to create the object, let's say a Person, and using Curl I submitted it to my application
我可以从控制器和哈希参数调用我想要的创建操作对象被正确传递
I'm able to call exactly the create action I want from the controller and the hash params of the object are being passed correctly
但现在我需要应用不同的行为,如果请求是否与XML,是什么困扰我是为什么在控制器请求。
But now I need to apply a different behaviour if request was made or not with XML, what is bothering me is why in the controller request.format gives "/".
任何线索?
curl -v -H "Content-Type: application/xml; charset=utf-8" --data-ascii @client.xml http://foo.com:3000/clients?api_key=xxx
def create
logger.debug request.format # produces "*/*"
if request.format.xml?
# never gets here
end
end
推荐答案
* / *
表示用户代理接受所有格式,不关心您提供的格式。我相信Safari这样做,等等。默认情况下, curl
发送 * / *
的Accept标头。
*/*
means that the user-agent accepts all formats and doesn't care what format you give it. I believe Safari does this, among others. By default, curl
sends an Accept header of */*
.
这里是头文件的转储 curl
默认发送:
Here is a dump of the headers curl
sends by default:
User-Agent: curl/7.18.1 (i386-apple-darwin9.6.0) libcurl/7.18.1 zlib/1.2.3
Host: example.com
Accept: */*
Content-Type:
但是,在这种情况下, XML如果发送给您的有效负载是XML?如果是这种情况,您想要直接检查请求的Content-Type头。
However, in this case, it looks like you want to send back XML if the payload sent to you was XML? If that's the case, you want to check the request's Content-Type header directly. i.e., request.content_type
is the method you want.
附录:我想到的是 request.content_type
更多关于这一点,我认为最好的方法是首先检查 request.format
,只有如果是不确定检查 request.content_type
。基本上,HTTP规范为客户端提供了能够告诉服务器我给你XML,但我想要回来的JSON。 Accept标头是客户端如何告诉你他们想要什么,如果有人实际发送它,你应该尊重。如果客户端没有指定,只使用请求的Content-Type作为提示。
Addenda: I thought a bit more about this, and I think the best approach is to first check request.format
and only if that is inconclusive check request.content_type
. Essentially, the HTTP spec provides for clients being able to tell servers that "I'm giving you XML, but I want JSON back." The Accept header is how clients tell you what they want back, and if someone actually sends it, you should honor that. Only use the request's Content-Type as a hint if the client didn't specify.
这篇关于request.format returns * / *的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!