Problem sending JSON data from JQuery to WCF REST method

后端 未结 5 638
小蘑菇
小蘑菇 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条回答
  • 2020-11-30 02:00

    I'll just post a short answer that helped me, because other answers didn't.

    • Scenario: ajax call to wcf service.
    • Error cause: automatic OPTIONS request from ajax before sending POST request. The first request could not be handled by my service.
    • Solution: allow OPTIONS request, and respond to it.

    What you need to do:

    1. Add this to web.config:

      <system.webServer>
      <httpProtocol>
        <customHeaders>
          <add name="Access-Control-Allow-Origin" value="*" />
          <add name="Access-Control-Allow-Methods" value="GET,PUT,POST,DELETE,OPTIONS" />
          <add name="Access-Control-Allow-Headers" value="Content-Type" />
        </customHeaders>
      </httpProtocol>
      

    2. Add this to Global.asax.cs (if you don't have this file in your solution, then create it by: Add new item => Visual C# => Global Application Class (default name is "Global.asax")):

      protected void Application_BeginRequest(object sender, EventArgs e)
      {
          if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
                          HttpContext.Current.Response.End();
      }
      
    0 讨论(0)
  • 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)

    0 讨论(0)
  • 2020-11-30 02:04

    Update:

    Try putting .svc after MyService so that the URL reads

    http://localhost/MyService.svc/PostSomething
    

    I was working on this the other day myself, and came across a post on Rick Strahl's blog:

    http://www.west-wind.com/weblog/posts/324917.aspx

    This works flawlessly for me, so give it a try!

    Hope that helps! :)

    0 讨论(0)
  • 2020-11-30 02:04

    In your web.config have you used webhttpbinding?

    only webhttpbinding supports json.

    0 讨论(0)
  • 2020-11-30 02:06

    This seems to be a Firefox thing for avoiding cross domain calls. See http://www.petefreitag.com/item/703.cfm

    The spec for this is here http://www.w3.org/TR/cors/ and after a very brief read, it appears that because you are doing a cross domain call, your service is expected to implement the OPTIONS method and return some headers that allow the POST method to be sent.

    0 讨论(0)
提交回复
热议问题