Problem sending JSON data from JQuery to WCF REST method

后端 未结 5 765
小蘑菇
小蘑菇 2020-11-30 01:27

I\'m having some trouble getting jquery to post some json data to a rest method I have on my WCF service.

On the WCF side, here\'s the operation contract:

         


        
5条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-30 02:03

    The update on the question containing a proposed solution has some issues - The problem with it is that if your input does not support the POST method, the OPTIONS request is not actually returning the correct allowed headers. It really isn't looking at which methods are actually allowed on the WCF endpoint - its just artificially saying "POST" is allowed for every single endpoint in the application when a client performs an OPTIONS request (which is really the client asking what is supported).

    This is probably OK, if you aren't really relying on the information in the OPTIONS method to return you a valid list of methods (as is the case with some CORS requests) - but if you are, you will need to do something like the solution on this question: How to handle Ajax JQUERY POST request with WCF self-host

    Basically, each endpoint should implement:

    Webinvoke(Method="OPTIONS", UriTemplate="")

    and call an appropriate method which loads the proper headers to the response (including the proper "Access-Control-Allow-Method" list for that endpoint) to the caller. It kind of sucks that hosted WCF endpoints don't do this for us automatically, but this is a workaround that allows finer control over the endpoint. In that solution the proper response headers are loaded at the endpoint implementation:

    public void GetOptions()
        {
            // The data loaded in these headers should match whatever it is you support on the endpoint
            // for your application. 
            // For Origin: The "*" should really be a list of valid cross site domains for better security
            // For Methods: The list should be the list of support methods for the endpoint
            // For Allowed Headers: The list should be the supported header for your application
    
            WebOperationContext.Current.OutgoingResponse.Headers.Add("Access-Control-Allow-Origin", "*");
            WebOperationContext.Current.OutgoingResponse.Headers.Add("Access-Control-Allow-Methods", "POST, GET, OPTIONS");
            WebOperationContext.Current.OutgoingResponse.Headers.Add("Access-Control-Allow-Headers", "Content-Type, Accept, Authorization");
        }
    

    In addition to that, you should be setting the "CrossDomainScriptAccessEnabled" flag either in the web.config for the binding endpoint, or in code for the WebHttpBinding when configuring the endpoint. Otherwise, you are again lying in your header response when you say "Access-Control-Allow-Origin" is "*" (or a list of URLS)

提交回复
热议问题