【发布时间】:2017-11-14 20:49:53
【问题描述】:
我正在尝试将数据发送到我的后端,但是当涉及到后端时,它会捕获一个异常,从而返回错误消息。 我假设这是因为来自客户端的数据格式与我预期的有所不同。
我希望我的后端接收 json 字符串(我有其他函数可以稍后将 jsong 字符串作为对象)。
我做错了什么?我知道我可以在后端为来自客户端的数据创建建模类,但我需要在没有它们的情况下工作,它应该工作,因为数据都是来自我的客户端的字符串 从客户。
客户
//to backend
callServer() {
var data = JSON.stringify(test);
//dispaly JSON like {"GradeA" : "23", "GradeB" : "45", "GradeC" : "22"}
console.log(data);
const headers = new HttpHeaders().set('Content-Type', 'application/json');
this.appService.http.post('http://localhost:2717/api/testAPi/test', data, {headers: headers})
.subscribe(data => {console.log(data), (err) => console.error("Failed! " + err);
})
}
后端
public class testAPiController : ApiController
{
private static readonly ILog Log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
public string test([FromBody] string body)
{
try
{
Log.Info(string.Format("data {0}", body));
//convert to json object
return json_object;
}
catch (Exception ex)
{
Log.Error(ex.Message);
return "error";
}
}
}
配置
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.MapHttpAttributeRoutes();
// Web API configuration and services
log4net.Config.XmlConfigurator.Configure();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { action = "GET", id = RouteParameter.Optional }
);
}
}
更新1
我没有收到任何错误消息,但将我的正文返回为 null
更新2
this.appService.http.post('http://localhost:2717/api/testAPi/test', "{\"GradeA\" : \"23\", \"GradeB\" : \"45\", \"GradeC\" : \"22\"}", {headers: headers})
当 Postman 使用它时,仍然不能使用不同格式的 body
【问题讨论】:
-
您希望从控制器中得到什么?因为现在你只会得到字符串:“ok”和“error”。 EDIT 自从发表此评论后,OP 已经编辑了他们的代码。
-
我希望在最后得到 json_object
-
异常的文本是什么?如果调试方法,body的值是多少?
-
正文为空,异常只返回“错误”
-
您应该摆脱
catch块并查看实际错误。