none
How to access WCF Self hosting by jquery ? RRS feed

  • Question

  • Hi:

    I try many times and study many document still not work, even I don't know what's problem. (I think maybe wcf configuration error)

    because the jquery will return

    readystate:4

    status:415

    statusText:"Cannot process the message because the content type 'application/json;charset=utf-8' was not the expected type 'text/xml; charset=utf-8'."

    I want execute console program and it will hosting wcf service at some port and listen...

    The other HTML or aspx or cshtml page will use jquery to access the wcf service.

    Can someone show me the complete sample code ? thanks

    Here are my sample code

    public interface IService
    {
     [OperationContract]
        [WebInvoke(Method = "POST",BodyStyle = WebMessageBodyStyle.Wrapped,ResponseFormat = WebMessageFormat.Json)]
        string GetData(int value);

    }

    --------------------------------------------------------------------------------------------------------------------

      <system.serviceModel>
        <services>
          <service name="Service">
            <endpoint address="mex" binding="mexHttpBinding" bindingConfiguration=""
              contract="IMetadataExchange" />
            <endpoint address="soap" binding="basicHttpBinding" bindingConfiguration=""
              contract="IService" />
            <endpoint address="rest" behaviorConfiguration="restBev" binding="webHttpBinding"
              bindingConfiguration="" contract="IService" />
          </service>
        </services>
        <behaviors>
          <endpointBehaviors>
            <behavior name="restBev">
              <webHttp />
            </behavior>
          </endpointBehaviors>
          <serviceBehaviors>
            <behavior name="">
              <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
              <serviceDebug includeExceptionDetailInFaults="false" />
            </behavior>
          </serviceBehaviors>
        </behaviors>
        <protocolMapping>
            <add binding="basicHttpsBinding" scheme="https" />
        </protocolMapping>   
        <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
      </system.serviceModel>

    -----------------------------------------------------------------------------------------------------------------

            static void Main(string[] args)
            {
                Uri httpBaseAddress = new Uri("http://localhost:12127/Service.svc");
                ServiceHost selfHost = new ServiceHost(typeof(WcfService1.Service1),httpBaseAddress);
                selfHost.Open();
                Console.WriteLine("Starting WCF....");
                Console.ReadLine();
            }

    ---------------------------------------------------------------------------------------------------------

                $.ajax({
               
                    type: "POST",
                    url: "http://localhost:12127/Service.svc/rest/GetData",
                    data: JSON.stringify({ value: 100 }),
                    contentType: "application/json;charset=utf-8",
                    dataType: "json",
                    success: function (data) {
                        console.log(data);
                        $("#result").text(data.GetDataResult);
                    },
                    error: function (error) {
                        console.log(error);
                        alert('error !!');
                    }
                });

    Thursday, November 26, 2015 11:30 PM

All replies

  • statusText:"Cannot process the message because the content type 'application/json;charset=utf-8' was not the expected type 'text/xml; charset=utf-8'."

    http://www.freeformatter.com/mime-types-list.html

    https://msdn.microsoft.com/en-us/library/bb472488%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396

    So, you have to make the WCF service know that JSON is coming and not text/xml use Bing or Google,  find articles about this and WCF.

    Friday, November 27, 2015 1:50 AM
  • Hi imacrl,

    According to this case, in my opinion, may be you can try to set the

    contentType: "application/json;charset=utf-8" ascontentType: "text/json",

    Then add the following attribute in your service file.

    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]

    For more information, please refer to the following articles:

    1.the content type 'application/json; charset=utf-8' was not the expected type 'text/xml; charset=utf-8'

    2.Calling WCF Services using jQuery

    Best Regards,

    Grady


    Friday, November 27, 2015 6:48 AM
    Moderator
  • Just enforce JSON on your endpoint, if you only need JSON, You can provide a ContentTypeMapper to your WCF.

    If you need other formats as well, you can implement Formatters.

    But first i suggest you set the RequestFormat = WebMessageFormat.JSON.

    Cheers

    Edit: i posted somewhat of a Code Guid (regarding the Formatter) in this post. Don't get scared away by all that posts and the Title of that Thread.

    The TypeMapper is pretty easy and straight forward, a quick google or msdn search should give you what you need.

    Edit2: oh and BTW, the ;charset=utf-8 is not needed and should not be written.
    • Edited by MDeero Friday, November 27, 2015 7:36 AM
    Friday, November 27, 2015 7:32 AM
  • try but still not work..
     the same error
    • Edited by imacrl Saturday, November 28, 2015 10:48 AM
    Saturday, November 28, 2015 10:47 AM
  • statusText:"Cannot process the message because the content type 'application/json;charset=utf-8' was not the expected type 'text/xml; charset=utf-8'."

    http://www.w3schools.com/json/

    https://api.jquery.com/jQuery.parseXML/

    http://www.xml.com/pub/a/2007/10/10/jquery-and-xml.html

    You know when push comes to shove? :)

    Sunday, November 29, 2015 8:28 AM
  • That's very little information to work on.

    I'd strongly advice you to get rid of the protocolMapping basicHttpsBinding (and instead just add an endpoint)

    (As I see it, you are using this to enable SSL on your endpoint, as far as i know, there's more to it than adding the Mapping. I believe it will not be SSL encrypted this way, it will just seem to use HTTPS as a prefix to it's base address. But i never seen this protcol mapping, so i can only assume stuff)

    Also you seem to have multiple Formats enabled. And i believe you want WCF to automatically select the appropriate Format, you'll have to tell it to:

    <behaviors>
      <endpointBehaviors>
        <behavior>
          <webHttp automaticFormatSelectionEnabled="true" />
        </behavior>
      </endpointBehaviors>
    </behaviors>

    or

    WebHttpBehavior webBehavior = new WebHttpBehavior();
    webBehavior.AutomaticFormatSelectionEnabled = true;
    sep.Behaviors.Add(webBehavior);


    Monday, November 30, 2015 7:41 AM