gpt4 book ai didi

c# - WCF Post 方法,返回 400 Bad Request

转载 作者:太空宇宙 更新时间:2023-11-03 12:37:00 25 4
gpt4 key购买 nike

我看到同一个问题有很多答案,但我无法解决我的问题,你们中的任何一个都可以通过我的代码解决我的问题吗?我创建了一个 WCF 服务如下POST 方法

接口(interface)(iComplaints.cs)

[OperationContract]
[WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.Bare, ResponseFormat = WebMessageFormat.Json, UriTemplate = "/insertcomplaint")]
Stream InsertComplaint(ComplaintData data);

类(Complaints.cs)

public Stream InsertComplaint(ComplaintData data)
{
//the code
}

DataContract 类(ComplaintData)

public class ComplaintData
{
[DataMember]
public string ComplaintID { get; set; }
[DataMember]
public string EntryBy { get; set; }
}

我在本地托管了该服务,当我尝试使用以下客户端方法使用它时,它给我 400(错误请求)

void PostComplaint()
{
HttpWebRequest req = null;
HttpWebResponse res = null;
string url = "http://localhost:28522/Complaints.svc/insertcomplaint";

ComplaintData iData = new ComplaintData();
iData.ComplaintID = txtComplaintID.Text;
iData.EntryBy = txtEntryBy.Text;

req = (HttpWebRequest)WebRequest.Create(url);
req.Method = "POST";
req.ContentType = "application/json";
req.Headers.Add("SOAPAction", url);

using (var streamWriter = new StreamWriter(req.GetRequestStream()))
{
streamWriter.Write(iData);
}

res = (HttpWebResponse)req.GetResponse();
using (var streamReader = new StreamReader(res.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
TextBox1.Text = result;
}
}

WCF 服务的 Web 配置

<service behaviorConfiguration="ServiceBehavior" name="Complaints">
<endpoint address="" behaviorConfiguration="webHttp" binding="webHttpBinding" contract="IComplaints" />
<endpoint contract="IMetadataExchange" binding="mexHttpBinding" address="mex" />
</service>

请任何人帮助。

最佳答案

我猜你的序列化有问题。请检查一下:

        void PostComplaint()
{
HttpWebRequest req = null;
HttpWebResponse res = null;
string url = "http://localhost:28522/Complaints.svc/insertcomplaint";

ComplaintData iData = new ComplaintData();
iData.ComplaintID = txtComplaintID.Text;
iData.EntryBy = txtEntryBy.Text;

req = (HttpWebRequest)WebRequest.Create(url);
req.Method = "POST";
req.ContentType = "application/json";
req.Headers.Add("SOAPAction", url);

using (var streamWriter = new StreamWriter(req.GetRequestStream()))
{
streamWriter.Write(Newtonsoft.Json.JsonConvert.SerializeObject(iData));
}

res = (HttpWebResponse)req.GetResponse();
using (var streamReader = new StreamReader(res.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
TextBox1.Text = result;
}

}

关于c# - WCF Post 方法,返回 400 Bad Request,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40564487/

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