【发布时间】:2018-04-20 16:36:29
【问题描述】:
我正在尝试从我的 Angular 应用程序执行 POST 到 .net Web API 实例,但服务器返回 null。
服务器
[HttpPost]
public string callBcknd([FromBody]string body)
{
try
{
Log.Info(string.Format("{0}", body));
}
catch(Exception ex)
{
return "error";
}
}
}
angular *请注意,我使用的是 HttpClient 而不是 Http.. 不确定这是否也是问题
callServer(){
var test = { "name": "John" }
let data = JSON.stringify(test);
let headers = new HttpHeaders();
headers.set('Content-Type', 'application/json');
this.appService.http.post('http://localhost:3000/api/WebApI/callBcknd',
test,
{headers: headers})
.subscribe(data => {console.log(data);}}}
配置
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new {action = "GET", id = RouteParameter.Optional}
);
}
}
通过上述设置,我不会在客户端生成任何 404 服务器错误(通过检查 chrome 的控制台),但它在后端返回 null。但是当我尝试使用 Postman 时,它会使用相同的 url 正确发送值。如果我在后端的方法中不包含 [FromBody],我会在客户端收到 404 服务器错误。此外,消息说“未找到与请求 URI 匹配的 HTTP 资源”。与此类似的问题似乎通过使用 [FromBody] 来解决问题,但我仍然得到一个空值......我还怀疑我的网络配置文件(不是上面的那个)应该包含一些标题,所以当我添加一些标题时,比如内容类型为 json 等然后我在客户端收到 500 服务器错误。在这一点上,我真的很困惑,不知道该怎么做。
更新1
以下服务器代码返回消息,但我仍然将正文设为 null.. 没有观察到错误
[HttpPost]
public IHttpActionResult Callbcknd([FromBody] string body)
{
try
{
Log.Info(string.Format("called with data {0}", body));
return Ok(new { Message = "It worked!" });
}
catch(Exception ex)
{
return base.Content(HttpStatusCode.InternalServerError, ex.ToString());
}
}
【问题讨论】:
-
这如何编译?您的 c# 方法返回类型
string并且唯一的返回语句在catch块中。此代码不应编译。
标签: c# angular asp.net-web-api