gpt4 book ai didi

.net - WCF HTTP POST 给出 HTTP 状态代码 400 : Bad Request

转载 作者:行者123 更新时间:2023-12-04 04:36:57 25 4
gpt4 key购买 nike

我正在创建一个 WCF 服务应用程序 (REST),它使用 HTTP POST 发送一个只包含字符串的 json,我在使用名为 PostMan 的程序发送一个 json 来测试服务时收到一个 HTTP 状态代码 400 错误请求,源代码如下:-

服务1.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 WcfImageUpload
{
// 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(UriTemplate = "/JsonData",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json, Method = "POST")]
bool SendData(JsonString JsonImage);

// TODO: Add your service operations here
}

// Use a data contract as illustrated in the sample below to add composite types to service operations.
[DataContract]
public class JsonString
{
[DataMember]
public string ImageData { get; set; }
}
}

服务1.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;

namespace WcfImageUpload
{
// 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 bool SendData(JsonString JsonImage)
{
return true;
}
}
}

网页配置
<configuration>
<system.serviceModel>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true"/>
<services>
<service behaviorConfiguration="Default" name="WcfImageUpload.Service1">
<endpoint address="" behaviorConfiguration="webBehavior" binding="webHttpBinding" contract="WcfImageUpload.IService1"/>
<endpoint contract="IMetadataExchange" binding="mexHttpBinding" address="mex"/>
</service>
</services>
<behaviors>
<endpointBehaviors>
<behavior name="webBehavior">
<webHttp helpEnabled="true"/>
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior name="Default">
<serviceMetadata httpGetEnabled="true"/>
</behavior>
<behavior name="">
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
<system.web>
<compilation debug="true"/></system.web></configuration>

请让我了解正在发生的事情。

最佳答案

错误的请求错误意味着您在请求中发送的数据格式不正确。

确保将请求的内容类型设置为 应用程序/json .

此外,将 WebMessageBodyStyle 设置为如下所示的包装请求,以便 WCF 服务期待包装的 JSON 字符串。默认情况下,它需要一个纯字符串。

[WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest)]

关于.net - WCF HTTP POST 给出 HTTP 状态代码 400 : Bad Request,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19589103/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com