C# HTTP/1.1 415 无法处理消息,因为内容类型为“application/json;charset=utf-8' 不是预期的类型 'text/xml; 字符集=utf-8'

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13617561/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 09:11:45  来源:igfitidea点击:

HTTP/1.1 415 Cannot process the message because the content type 'application/json; charset=utf-8' was not the expected type 'text/xml; charset=utf-8'

c#wcf

提问by Keat Choon

trying to POST json dictionary to C# WCF, when i invoke it HTTP Response 415. Someone can tell me whats wrong with my code.

尝试将 json 字典发布到 C# WCF,当我调用它时 HTTP 响应 415。有人可以告诉我我的代码有什么问题。

object Class

对象类

 [DataContract]
public class Class1
{
    [DataMember]
    public string AccNo;
     [DataMember]
    public string CompanyName;
     [DataMember]
    public string DocDate;
}

IService1.cs

服务1.cs

   [OperationContract]
    [WebInvoke(Method = "POST", UriTemplate = "json/PostSalesOrderData", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare)]
        string PostSalesOrderData(string data);

Service1.svc.cs

服务1.svc.cs

 public string PostSalesOrderData(string data)
    {

        JavaScriptSerializer serializer = new JavaScriptSerializer();

        Dictionary<string, Class1> dict = serializer.Deserialize<Dictionary<string, Class1>>(data);

        return dict["Debtor"].AccNo.ToString();
    }

Fiddle Details

小提琴细节

HTTP/1.1 415 Cannot process the message because the content type 'application/json; charset=utf-8' was not the expected type 'text/xml; charset=utf-8'. Server: Microsoft-IIS/7.5 X-Powered-By: ASP.NET Date: Thu, 29 Nov 2012 01:21:55 GMT Content-Length: 0

HTTP/1.1 415 无法处理消息,因为内容类型为“application/json;charset=utf-8' 不是预期的类型 'text/xml; 字符集=utf-8'。服务器:Microsoft-IIS/7.5 X-Powered-By:ASP.NET 日期:2012 年 11 月 29 日星期四 01:21:55 GMT 内容长度:0

采纳答案by carlosfigueira

The endpoint for your service is not properly configured to receive JSON input. In order for the [WebInvoke]attribute to be honored, your endpoint needs to have the webHttpBinding, and it should also have an endpoint behavior of type <webHttp/>

您的服务的端点未正确配置为接收 JSON 输入。为了使该[WebInvoke]属性受到尊重,您的端点需要具有webHttpBinding,并且还应该具有类型为的端点行为<webHttp/>

One easy way to ensure that it's properly configured is to use the Factoryattribute on the .svc file. Something like the example below:

确保正确配置的一种简单方法是使用Factory.svc 文件上的属性。类似于下面的例子:

<%@ ServiceHost Language="C#" Debug="true"
                Service="YourNamespace.YourServiceClass"
                Factory="System.ServiceModel.Activation.WebServiceHostFactory" %>