我已经实现了一个WCF RESTful Web服务,该服务在"POSTMAN"
期间通过原始主体获取参数。当通过JavaScriptSerializer ser = new JavaScriptSerializer();
var request = (HttpWebRequest)WebRequest.Create("http://192.168.0.19/SSARESTservice/SSA/IMEIVerification");
request.Method = "POST";
request.ContentType = "application/json";
DeviceData data = new DeviceData() { IMEI = "352423061590616" };
string str = ser.Serialize(data);
byte[] databyte = System.Text.Encoding.UTF8.GetBytes(str);
request.ContentLength = databyte.Length;
var reqStrm = request.GetRequestStream();
reqStrm.Write(databyte, 0, databyte.Length);
var response = (HttpWebResponse)request.GetResponse();
var respStrm = response.GetResponseStream();
StreamReader reader = new StreamReader(respStrm);
string bodyprm = reader.ReadToEnd();
chrome扩展进行测试时,它会提供所需的结果,如下图所示:
现在,我希望通过使用以下代码的ASP Web应用程序使用相同的服务获得相同的结果
var response = (HttpWebResponse)request.GetResponse();
但执行上述代码时会出现以下错误
远程服务器返回错误:(400)错误请求。
描述:执行当前Web请求期间发生了未处理的异常。请查看堆栈跟踪以获取有关错误及其源自代码的位置的更多信息。
异常详细信息:System.Net.WebException:远程服务器返回错误:(400)错误请求。
第34行:[WebInvoke(UriTemplate = "IMEIVerification", Method = "POST", ResponseFormat= WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json,BodyStyle=WebMessageBodyStyle.WrappedRequest)
[OperationContract]
JsonResponseProps VerifyDevice(DeviceData data);
这是我的操作合同
public JsonResponseProps VerifyDevice(DeviceData data)
{
JsonResponseProps jis = new JsonResponseProps();
using (con = new SqlConnection(connection))
{
con.Open();
cmd = new SqlCommand("select IMEI from dbo.tbl_master_Devicedata where IMEI='" + data.IMEI + "'", con);
var IMEI = cmd.ExecuteScalar();
if (IMEI != null)
{
jis.msg = "Verification Successful";
jis.success = "true";
}
else
{
jis.msg = "Verification Failed";
jis.success = "false";
}
con.Close();
}
return jis;
}
实施
<input type="file" custom-on-change="uploadFile">
谢谢
答案 0 :(得分:2)
问题在于,使用POSTMAN发送:
{"data":{"IMEI":"352423061590616"}}
但是从
检查序列化数据时JavaScriptSerializer ser = new JavaScriptSerializer();
DeviceData data = new DeviceData() { IMEI = "352423061590616" };
string str = ser.Serialize(data);
您将看到有线格式:
{"IMEI":"352423061590616"}
这并不能很好地映射到你的data
参数。
要解决此问题,请为Root容器添加一个额外的类。它具有类型DeviceData
的数据属性,用于保存实际有效负载。序列化的代码如下所示:
// container with a data property
// this one is being serialized
public class Root
{
public DeviceData data { get; set; }
}
public class DeviceData
{
public string IMEI { get; set; }
}
protected void CallIMEIVerfication()
{
JavaScriptSerializer ser = new JavaScriptSerializer();
DeviceData data = new DeviceData() { IMEI = "352423061590616" };
var root = new Root { data=data };
string str = ser.Serialize(root);
// rest of your code
}