开发者

RESTful.NET service and preflight

I'm developing a RESTful web service with WCF and C#. The service works fine, but when I made a request from a static HTML page, using XMLHttpRequest, all browsers except IE (who else?) first send a prefligth message (https://developer.mozilla.org/en/http_access_control) requesting the available options for the service. This kind of messages only occur when I change the headers of the message in order to send a POST request.

My question/suggestion: do you know any way to give support to this kind of messages on WCF/.NET? My idea is to implement a method to handle the preflight message; the reply would be a standard reply message with all th开发者_运维知识库e available options (GET, PUT, POST, DELETE), because all this operations will be available, and also tells that the only type of data available for the data on the messages is JSON. After the reply the normal request would be sent by the browser, so everything should work right.

What do you think?


You can support OPTIONS in the same way you support POST with the WebInvoke attribute. Just change the method. There is nothing special about the OPTIONS request. You just need to set the Allow header in the response.


Problem solved! I've setted the Method attribute with * and now it works fine: first the preflight request is answered and then the real request is received and handled. Code follows:

[OperationContract]
[WebInvoke(UriTemplate="*", Method = "*")]
void HandleHttpOptionsRequest();


[OperationContract]
[WebInvoke(UriTemplate="*", Method = "*")]
void HandleHttpOptionsRequest();

This is a great solution and you can implement an IDispatchMessageInspector to add the necessary CORS headers quite easily.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜