内容类型“application/json; charset=utf-8”与预期类型“text/xml; charset=utf-8”不符。

7
使用Firebug时,我在我的ASP.NET MVC 4项目中遇到了一个奇怪的错误:“NetworkError: 415无法处理...xt / xml; charset = utf-8'。 - http://localhost:59899/wsccc1/wscccService.svc/RunTts ”。
代码:
<script lang="javascript" type="text/javascript">
    function ttsFunction() {
        serviceUrl = "http://localhost:59899/wsccc1/wscccService.svc/RunTts";
        var data = new Object();
        data.text = $('#speak').val();
        var jsonString = JSON.stringify(data);
        $.ajax({
            type: 'POST',
            url: serviceUrl,
            data: jsonString,
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            success: function() { alert('ok')},
            error: function (xhr,status,error) {
                console.log("Status: " + status);
                console.log("Error: " + error);
                console.log("xhr: " + xhr.readyState);
            },
            statusCode: {
                404: function() {
                    console.log('page not found');
                }
            }
        });
    }
</script>

服务代码:
 [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
[ServiceBehavior(IncludeExceptionDetailInFaults = true)]
public class wservice:Iwservice
{
    public string RunTts(string value)
    {
        return value.ToUpper();
    }
}

接口是:

namespace service
{
     [ServiceContract]
     public interface Iwservice
     {
        [OperationContract]
        [WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped, UriTemplate = "RunTts")]
        string RunTts(string text);
     }
}

关于 Web Config,我在 WCF 中使用了无文件方式。

<?xml version="1.0"?>
<configuration>
  <system.web>
    <compilation debug="true" targetFramework="4.5"/>
    <httpRuntime targetFramework="4.5"/>
  </system.web>
  <system.serviceModel>
    <serviceHostingEnvironment >
       <serviceActivations>
         <add factory="System.ServiceModel.Activation.ServiceHostFactory" 
     relativeAddress="./wsccc1/wscccService.svc" 
     service="service.wservice"/>
      </serviceActivations>
    </serviceHostingEnvironment>
   <behaviors>
     <serviceBehaviors>
        <behavior>
          <serviceMetadata httpGetEnabled="true"/>
        </behavior>
     </serviceBehaviors>
   </behaviors>
  </system.serviceModel>
</configuration> 

wsservice类是否在service命名空间中?如果不是,则无法匹配服务激活。 - carlosfigueira
是的,我没有在代码中输入它。当我在浏览器中输入http://localhost:59899/wsccc1/wscccService.svc时,它确实可以工作。 - user1108948
你是否缺少webHttpBehavior? - Praburaj
它不在web.config文件中吗?我需要手动添加它,应该在哪里添加? - user1108948
是的。我相信您还没有定义服务端点。根据您正在访问的内容,您应该为此服务配置一个webHttpBinding,并且此端点应该具有一个端点行为,其中<webHttp/>在其下定义。它抛出此错误的原因可能是您试图像访问REST端点一样访问SOAP端点(默认端点)。 - Praburaj
你能提供一个答案吗?我需要代码。该服务是一个类库文件,我没有 svc 文件,因为我在 WCF 4 中使用了无文件。 - user1108948
2个回答

11

你需要在代码中使用WebServiceHostFactory而不是常规的ServiceHostFactory。这将使用适当的绑定(webHttpBinding)和行为(webHttp)配置端点,以遵守[WebInvoke]属性。

<serviceHostingEnvironment >
   <serviceActivations>
     <add factory="System.ServiceModel.Activation.WebServiceHostFactory"
          relativeAddress="./wsccc1/wscccService.svc" 
          service="service.wservice"/>
  </serviceActivations>
</serviceHostingEnvironment>

在我的情况下,我遇到了同样的问题,只有在尝试从jquery调用我的服务时才会出现。为什么我还没有WebServiceHostFactory,但通过Fiddler进行相同类型的调用却可以正常工作? - PositiveGuy
var settings = { "async": true, "crossDomain": true, "url": "http://bschoolapp.azurewebsites.net/Service1.svc", "method": "POST", "headers": { "soapAction": "http://tempuri.org/IService1/GetAnswers", "Content-Type": "application/json", "Cache-Control": "no-cache", "Postman-Token": "5ea26881-e357-4501-a503-3e907ad1448d" }, "processData": false, "data": "{"queNumber":"5","answer":"sample answer","studentID":"11111"}" }$.ajax(settings).done(function (response) { console.log(response); }); - Kanes

4

请前往您的 web.config 端点标记,并检查 bindingConfiguration 是否正确存在,同时确保地址拼写正确。

<endpoint address="/YourName".../>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接