在Javascript中将JSON对象保存到WCF REST服务 [英] Saving JSON object to WCF REST SERVICES in Javascript

查看:92
本文介绍了在Javascript中将JSON对象保存到WCF REST服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个chrome扩展,因为我想在javascript中将JSON对象发送到WFC REST服务(.svc)。我的javascript代码低于





  var  myRequest =  new  XMLHttpRequest(); 

myRequest.onreadystatechange = function(){
if (myRequest.readyState == 4 && myRequest.status == 200 ){
console.log( ' 发送到服务器:' + dataString + ' );
window.localStorage.removeItem(dataString);
}
else if (myRequest.readyState == 4 && myRequest.status!= 200 ){

console.log(' 服务器请求无法完成');
saveDataLocally(dataString);
}
}

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





 dataString是一个JSON对象
dataString ={firstName:suresh,lastName:kumar}



我得到错误
POST http:// localhost:8221 / Service1.svc / SaveData 415(不支持的媒体类型)





在我的网上服务

 Service1.svc.cs 







 使用系统; 
使用 System.Collections.Generic;
使用 System.Linq;
使用 System.Runtime.Serialization;
使用 System.ServiceModel;
使用 System.ServiceModel.Web;
使用 System.Text;
使用 OfflinetoOnlineService.ServiceReference1;

命名空间 OfflinetoOnlineService
{
// < span class =code-comment>注意:您可以使用重构菜单上的重命名命令将代码,svc和配置文件中的类名Service1一起更改。
public class Service1:IService1
{
public object SaveData(Offline dataString)
{
string strmessage = string .Empty;
if (dataString!= null
{
strmessage = dataString.dataString + datastring得到它;

}
return strmessage;
}


}
}





 IService1.cs 





 使用系统; 
使用 System.Collections.Generic;
使用 System.Linq;
使用 System.Runtime.Serialization;
使用 System.ServiceModel;
使用 System.ServiceModel.Web;
使用 System.Text;

命名空间 OfflinetoOnlineService
{
// < span class =code-comment>注意:您可以使用重构菜单上的重命名命令在代码和配置文件中一起更改接口名称IService1。
[ ServiceContract]
public interface IService1
{

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


}

[DataContract]
public 离线
{
对象 data = string .Empty;
[DataMember]
public object dataString
{
获取 {返回数据; }
set {data = value ; }
}
}


}



 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 = < span class =code-string> 524288最大值ReceivedMessageSize = 65536
messageEncoding = Text textEncoding = utf-8 transferMode = 缓冲
useDefaultWebProxy = true >
< readerQuotas maxDepth = 32 maxStringContentLength = 8192 maxArrayLength = 16384
maxBytesPerRead = 4096 maxNameTableCharCount = 16384 />
< security mode = >
< transport clientCredentialType = proxyCredentialType =
realm = />
< message clientCredentialType = UserName algorithmSuite = 默认 />
< / 安全 >
< / binding >
< / basicHttpBinding >
< / bindings >
< client>
< endpoint address = http:// localhost:8221 / Service1.svc binding = basicHttpBinding
bindingConfiguration = BasicHttpBinding_IService1 contract = ServiceReference1.IService1
name = BasicHttpBinding_IService1 />
< / 客户 >
< services>
< service name = OfflinetoOnlineService.Service1 behaviorConfiguration = myServiceBehavior >
<! - 服务端点 - >
< endpoint address = binding = basicHttpBinding contract = OfflinetoOnlineService .IService1 >
< identity>
< dns value = localhost />
< / identity >
< / endpoint >
< endpoint address = mex binding = mexHttpBinding contract = IMetadataExchange接口 />
< / 服务 >
< / services >
< behavior>
< serviceBehaviors>
< behavior name = myServiceBehavior >
< serviceMetadata httpGetEnabled = true />
< serviceDebug includeExceptionDetailInFaults = false />
< / 行为 >
< behavior>
<! - 为了避免公开元数据信息,设置 以下 false
删除上面的元数据端点 - >
< serviceMetadata httpGetEnabled = true />
<! - 要接收 以进行调试,设置为 true 。在部署之前设置为 false 以避免泄露异常信息 - >
< serviceDebug includeExceptionDetailInFaults = false />
< / 行为 >
< / serviceBehaviors >
<! - < endpointBehaviors>
< behavior name = webHttp >
< webHttp />
< / 行为 >
< / endpointBehaviors > - >
< / 行为 >
< serviceHostingEnvironment multipleSiteBindingsEnabled = true />
< / system.serviceModel >
< system.webServer>
< modules runAllManagedModulesForAllRequests = true />
< / system.webServer >

< / configuration >





请指导我如何保存该JSON对象到我的Web服务(.svc)

解决方案

它们可能是您的问题的多种原因。其中一个问题可能如下面的链接所示。



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

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



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




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



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; }
        }
    }

   
}


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) 

解决方案

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


这篇关于在Javascript中将JSON对象保存到WCF REST服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆