Click here to Skip to main content
15,662,782 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I am creating a chrome extension , in that i want to send a JSON object to WFC REST Services(.svc) in javascript. My javascript code below


C#
var myRequest = new XMLHttpRequest();

    myRequest.onreadystatechange=function() {
        if (myRequest.readyState == 4 && myRequest.status == 200) {
            console.log('Sent to server: ' + dataString + '');
            window.localStorage.removeItem(dataString);
        }
        else if (myRequest.readyState == 4 && myRequest.status != 200) {

            console.log('Server request could not be completed');
            saveDataLocally(dataString);
        }
    }

    myRequest.open("POST","http://localhost:8221/Service1.svc/SaveData",true);
        myRequest.setRequestHeader("Content-Type","application/json");
        myRequest.send(dataString);


dataString is a JSON object
dataString = "{"firstName":"suresh","lastName":"kumar"}"

Im getting Error
POST http://localhost:8221/Service1.svc/SaveData 415 (Unsupported Media Type)


In My Web Service
Service1.svc.cs



C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using OfflinetoOnlineService.ServiceReference1;

namespace OfflinetoOnlineService
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in code, svc and config file together.
    public class Service1 : IService1
    {
           public object SaveData(Offline dataString)
        {
            string strmessage = string.Empty;
            if (dataString != null)
            {
                strmessage = dataString.dataString + "datastring got it";
               
            }
            return strmessage;
        }

      
    }
}


IService1.cs


C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;

namespace OfflinetoOnlineService
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IService1" in both code and config file together.
    [ServiceContract]
    public interface IService1
    {

        [OperationContract]
        [WebInvoke(Method = "POST", UriTemplate = "/SaveData", RequestFormat = WebMessageFormat.Json,
            ResponseFormat = WebMessageFormat.Json)]
          object SaveData(Offline dataString);

     
    }

    [DataContract]
    public class Offline
    {
        object data = string.Empty;
        [DataMember]
        public object dataString
        {
            get { return data; }
            set { data = value; }
        }
    }

   
}

C#
Web.config

<?xml version="1.0"?>
<configuration>

  <system.web>
    <compilation debug="true" targetFramework="4.0" />
  </system.web>
  <system.serviceModel>
    <bindings>
      <basicHttpBinding>
        <binding name="BasicHttpBinding_IService1" closeTimeout="00:01:00"
          openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
          allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
          maxBufferSize="65536" maxBufferPoolSize="524288" maxReceivedMessageSize="65536"
          messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered"
          useDefaultWebProxy="true">
          <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
            maxBytesPerRead="4096" maxNameTableCharCount="16384" />
          <security mode="None">
            <transport clientCredentialType="None" proxyCredentialType="None"
              realm="" />
            <message clientCredentialType="UserName" algorithmSuite="Default" />
          </security>
        </binding>
      </basicHttpBinding>
    </bindings>
    <client>
      <endpoint address="http://localhost:8221/Service1.svc" binding="basicHttpBinding"
        bindingConfiguration="BasicHttpBinding_IService1" contract="ServiceReference1.IService1"
        name="BasicHttpBinding_IService1" />
    </client>
    <services>
      <service name="OfflinetoOnlineService.Service1" behaviorConfiguration="myServiceBehavior">
        <!-- Service Endpoints -->
        <endpoint address="" binding="basicHttpBinding" contract="OfflinetoOnlineService.IService1">
          <identity>
            <dns value="localhost"/>
          </identity>
        </endpoint>
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="myServiceBehavior" >
          <serviceMetadata httpGetEnabled="true"/>
          <serviceDebug includeExceptionDetailInFaults="false"/>
        </behavior>
        <behavior>
          <!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
          <serviceMetadata httpGetEnabled="true"/>
          <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
          <serviceDebug includeExceptionDetailInFaults="false"/>
        </behavior>
      </serviceBehaviors>
      <!--<endpointBehaviors>
        <behavior name="webHttp">
          <webHttp/>
        </behavior>
      </endpointBehaviors>-->
    </behaviors>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
     </system.serviceModel>
 <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
  </system.webServer>
  
</configuration>


Please Guide me how to Save that JSON object to my Web service(.svc) 
Posted
Updated 3-Jul-13 0:15am
v2

1 solution

Their can be multiple reasons for your problem. One of the problem could be as mentioned in below link.

http://stackoverflow.com/questions/11477420/415-unsupported-media-type-calling-wcf-service-from-ajax
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900