How to respond to an HTTP OPTIONS request?

2019-02-11 09:26发布

The HTTP OPTIONS method is supposedly used to determine what other methods the server supports on a given resource. Given that, I have two questions:

  • What does this response look like? I have seen examples with CSV lists in Public, Allow, and even Access-Control-Allow-Methods headers. Are they all needed? What's the difference? RFC 2616 doesn't seem to be very helpful here.

  • Would it be appropriate to use this to list the actions that a resource supports in a non-REST-API environment? For example, if my ConversionController supports the action convert, would a response like this make sense:

Request:

OPTIONS /conversion HTTP/1.1

Response:

HTTP/1.1 200 OK
...
Allow: CONVERT
...

标签: http
2条回答
干净又极端
2楼-- · 2019-02-11 10:05

In response to the title: "How to respond to an HTTP OPTIONS request?" To answer that, I'd want to know why you want to respond to an OPTIONS request? Who/what is sending you an OPTIONS request, and why? Many public servers respond with some form of "error" or "not allowed" (500, 501, 405). So, unless you're in a specific situation where your clients will be reasonably sending OPTIONS requests and expecting useful/meaningful information back (e.g., WebDAV, CORS), you probably want to respond with: "don't do that."

In terms of your question about the "OPTIONS /conversion HTTP/1.1" request: unless you know that there's some client of your server, a client which would send an OPTIONS request to "/conversion" and expect a response with "Allow: CONVERT," the answer is no: it wouldn't make sense to respond like that. I think that most implementations that do support OPTIONS and respond with "Allow," respond with standard HTTP methods.

Here's a great article on the topic.

Summary: OPTIONS is immediately problematic because it doesn't support caching. Alternatives: server-wide metadata: try well-known URI's. Resource-specific: try using a Link header on its responses, or a link in the representation format for that resource.

Lastly, if what you're after is a service description, have a look at WADL or RSDL.

EDIT:

dotnetguy makes a good point in the comment below: OPTIONS is undeniably valuable in certain contexts (e.g., CORS); I certainly didn't mean to suggest otherwise.

查看更多
Emotional °昔
3楼-- · 2019-02-11 10:15

RFC 2616 defines "Allow" (http://greenbytes.de/tech/webdav/rfc2616.html#rfc.section.14.7). "Public" is not in use anymore. "Access-Control-Allow-Methods" is defined in the CORS specification (see http://www.w3.org/TR/cors/).

查看更多
登录 后发表回答