C# 无法处理消息,因为内容类型为“application/json;” charset=utf-8' 不是预期的类型 'text/xml; 字符集=utf-8'
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14403492/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Cannot process the message because the content type 'application/json; charset=utf-8' was not the expected type 'text/xml; charset=utf-8'
提问by Mark C
I am get the above response when calling a WCF service via ajax json. My calling code is:
通过ajax json调用WCF服务时得到上述响应。我的调用代码是:
<script type="text/javascript">
$(document).ready(function () {
$.ajax
({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "http://localhost:90/WebServices/UserService.svc/Calculate",
data: "{}",
timeout: 10000,
dataType: "json",
success: function (response) {
alert(response)
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.statusText);
alert(thrownError);
}
});
});
</script>
My service is:
我的服务是:
[ServiceContract]
public interface IUserService
{
[OperationContract]
[WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.Wrapped, ResponseFormat = WebMessageFormat.Json
)]
Answer Calculate();
}
[DataContract]
public class Answer
{
[DataMember]
public string answer { get; set; }
}
My method is :
我的方法是:
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
[ServiceBehavior(IncludeExceptionDetailInFaults = true)]
public class UserService : IUserService
{
public Answer Calculate()
{
Answer answer = new Answer();
answer.answer="Hello World";
return answer;
}
}
I have been battling with for sometime, I see other people have had the same type problem and I tried all there suggestions but still nothing is working.
我一直在与之抗争一段时间,我看到其他人也遇到了相同类型的问题,我尝试了所有建议,但仍然没有任何效果。
Where is the problem? How can I solve it?
问题出在哪儿?我该如何解决?
回答by carlosfigueira
I'm guessing here since you didn't show how you defined your endpoint, but I'm pretty sure it's the case. Your endpoint is not defined for web consumption - it's likely using basicHttpBinding
. To consume the endpoint via jQuery (or other web/REST clients in general) you need to define an endpoint with the WebHttpBinding
, and apply the WebHttpBehavior
to it.
我在这里猜测是因为您没有展示如何定义端点,但我很确定情况确实如此。您的端点不是为 Web 消费定义的 - 它很可能使用basicHttpBinding
. 要通过 jQuery(或其他一般的 Web/REST 客户端)使用端点,您需要使用 定义端点WebHttpBinding
,并将 应用WebHttpBehavior
到它。
There are different ways to define the endpoint correctly. The easiest one is to use the WebServiceHostFactory
in your .svc file:
有多种方法可以正确定义端点。最简单的方法是WebServiceHostFactory
在 .svc 文件中使用:
UserService.svc:
用户服务.svc:
<%@ ServiceHost Language="C#" Debug="true" Service="YourNamespace.UserService"
Factory="System.ServiceModel.Activation.WebServiceHostFactory" %>
回答by Corey
For anyone who lands here by searching: 'content type 'application/json; charset=utf-8' was not the expected type 'text/xml; charset=utf-8'
对于通过搜索登陆这里的任何人:“内容类型”应用程序/json;charset=utf-8' 不是预期的类型 'text/xml; 字符集=utf-8'
A similar error was caused in my case by building and running a service without proper attributes. I got this error message when I tried to update the service reference in my client application. It was resolved when I correctly applied '[DataContract]' and '[DataMember]' attributes to my custom classes.
在我的案例中,由于构建和运行没有适当属性的服务而导致了类似的错误。当我尝试更新客户端应用程序中的服务引用时收到此错误消息。当我正确地将 '[DataContract]' 和 '[DataMember]' 属性应用于我的自定义类时,它得到了解决。
Edit: This would most likely be applicable if your service was set up and working and then it broke after you edited it.
编辑:如果您的服务已设置并正常工作,然后在您编辑后中断,这很可能适用。
回答by HeyJude
This is a pretty old question, but I'd like to add some information upon @carlosfigueira answer.
这是一个很老的问题,但我想在@carlosfigueira 的回答中添加一些信息。
1. Specifying Factory
in .svc
vs. specifing a <service>
in web.config
1. 指定Factory
输入.svc
与指定<service>
输入web.config
The alternative to specifying a Factory
in the .svc
file is specifying a <service>
in the web.config
file. This is explained in many other answers (e.g. this one), so I won't repeat them, but it worth copying here yet another @carlosfigueira answer:
到指定的替代Factory
的在.svc
文件被指定一个<service>
中web.config
的文件。这在许多其他答案中都有解释(例如这个),所以我不会重复它们,但值得在这里复制另一个@carlosfigueira答案:
If you don't specify any factory in the .svc file, all the endpoints will come from the web.config file - WCF will try to find a
<system.serviceModel / service>
element whosename
attribute matches the fully-qualified nameof the service class. If it doesn't find one, then it will add a default endpoint (usingbasicHttpBinding
, unless you changed the default mapping).
如果您未在 .svc 文件中指定任何工厂,则所有端点都将来自 web.config 文件 - WCF 将尝试查找
<system.serviceModel / service>
其name
属性与服务类的完全限定名称匹配的元素。如果没有找到,它将添加一个默认端点(使用basicHttpBinding
,除非您更改了默认映射)。
And to be clear: the fully-qualified nameshould include the namespace. So if one has the following, it would be MyWebServices.ExampleWebService
:
需要明确的是:完全限定的名称应该包括命名空间。所以如果有以下情况,那就是MyWebServices.ExampleWebService
:
namespace MyWebServices
{
[ServiceContract]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
[ServiceBehavior(IncludeExceptionDetailInFaults = true)]
public class ExampleWebService
{
[OperationContract]
[WebInvoke(Method = "POST",
BodyStyle = WebMessageBodyStyle.Bare,
ResponseFormat = WebMessageFormat.Json,
RequestFormat = WebMessageFormat.Json)]
public string DoWork(DoWorkRequest request)
{
return "success!";
}
}
}
2. Getting "Cannot process the message..." when called on localhost
2. 在本地主机上调用时出现“无法处理消息...”
I came to this question when trying to run an ajax call on localhost from Visual Studio, and got the error message which is the title of this question, so I'd like to list the required steps to solve it:
我在尝试从 Visual Studio 对 localhost 运行 ajax 调用时遇到了这个问题,并得到了这个问题的标题的错误消息,所以我想列出解决它所需的步骤:
- As explained above, either add a
Factory
in the.svc
, or specify what's needed in theweb.config
. - In Visual Studio, right-click your
.html
file, and select "View in Browser". Your default browser would open, and if it's Chrome, the url would be, e.g,localhost:51667/test.html
(which is actuallyhttp://localhost:51667/test.html
). - You can now fire your ajax call, and hopefully, you'd get your web service response successfully.
- If you'd like to debug your web service, then:
In Visual Studio, make sure that the web service's project is set as the Startup Project, and hit F5. This would start WCF Test Client window, but you can just ignore it and fire your ajax request.
- 如上所述,无论是添加
Factory
的.svc
,或指定我们所需要的web.config
。 - 在 Visual Studio 中,右键单击您的
.html
文件,然后选择“在浏览器中查看”。您的默认浏览器将打开,如果是 Chrome,则 url 将是,例如localhost:51667/test.html
(实际上是http://localhost:51667/test.html
)。 - 您现在可以触发 ajax 调用,希望您能成功获得 Web 服务响应。
- 如果您想调试 Web 服务,则:
在 Visual Studio 中,确保将 Web 服务的项目设置为启动项目,然后按 F5。这将启动 WCF 测试客户端窗口,但您可以忽略它并触发您的 ajax 请求。