简体   繁体   中英

Issue with calling WCF cross domain

I'm trying to call a WCF service cross-domain using javascript, over http.

I've added the Access-Control-Allow-Origin header to the operation I want to call like so:

WebOperationContext.Current.OutgoingResponse.Headers.Add("Access-Control-Allow-Origin", "*");

However when I post using jquery.ajax I get:

Origin http://server/ is not allowed by Access-Control-Allow-Origin.

What's worse is it even happens from my local machine:

XMLHttpRequest cannot load http://localhost:8201/wcfservice. Origin http://localhost/ is not allowed by Access-Control-Allow-Origin. (observed in Chrome)

am I doing something fundamentally wrong?

What you're doing is fine for GET requests (in CORS-enabled browsers) - the request is sent to the service, and the browser will let it back to the application if the service has the Access-Control-Allow-Origin header).

For "unsafe" requests (ie, those which can potentially cause side effects in the service, such as POST, PUT and DELETE), the browser first sends a preflight request, an OPTIONS request which "asks" the service whether it can accept a cross-domain request. Since your operation only responds to POST requests, it won't respond to that request and the browser will block it.

I wrote a post about one way of implementing CORS support in WCF, you can find it at http://blogs.msdn.com/b/carlosfigueira/archive/2012/05/15/implementing-cors-support-in-wcf.aspx . Basically, you'll need to handle the OPTIONS requests as well, in addition to the "normal" requests.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM