找不到Angular2 POST Web api 404

我正在构建一个Angular2服务来记录存储在ILog对象中的某些事件,并将它们发送到API以存储在数据库中。

我的日志服务非常简单:

import { Injectable } from '@angular/core'; import { Http } from '@angular/http'; import { EnvironmentModule } from "../environment"; import { ILog } from "./log"; @Injectable() export class LogService { constructor(private _http: Http, private environment: EnvironmentModule) { } postLog(log: ILog): void { this.json = this.convertToJSON(log); this._http.post(this.environment.getWebApiUri() + 'api/Log/PostLog/', log, {}) .subscribe( () => console.log('Success') ); //goes to localhost:3304/WebAPI/Log/PostLog/, returns 404 not found } } 

它调用WebAPI控制器将数据传递给要处理的服务:

 [RoutePrefix("api/Log")] public class LogController : ApiController { private ILogService _LogService; public LogController() : this(new LogService()) { } //constructor public LogController(ILogService LogService) { _LogService = LogService; } //constructor [HttpPost()] [Route("PostLog")] public void PostLog(Log log) { _LogService.PostLog(log); } //PostLog } //class 

然而,当我的服务调用API时,它会抛出404 Not Found Error。

导航到浏览器中的路径我看到:

   No HTTP resource was found that matches the request URI 'http://localhost:3304/WebAPI/api/Log/PostLog/'.   No action was found on the controller 'Log' that matches the request.   

谁能帮我这个? 我不明白为什么这样做。

因为你不能将primefaces值作为json直接发布到你的方法中。 您可以将其转换为对象,然后将其作为相应的对象发布,或者将其作为uri编码的forms发布,也可以使用。 这是asp.net的web api的限制。

还有一些其他类似的问题都有类似的答案。 以下是如何将其更改为工作的快速示例。

c#代码

 [HttpPost()] [Route("PostLog")] public void PostLog(LogContainerModel logModel) { _LogService.PostLog(logModel.log); } // model public sealed class LogContainerModel { public string log { get; set; } } 

javascript代码

 private convertToJSON(log: ILog): string { return JSON.stringify({log: log}); } 

选项2

根据之前的SO答案将其字符串化为对象。

c#代码

 [HttpPost()] [Route("PostLog")] public void PostLog([FromBody] string jsonString) 

javascript代码

 private convertToJSON(log: ILog): string { return JSON.stringify({'': log}); // if that does not work try the snippet below // return JSON.stringify({'': JSON.stringify(log)}); } 

选项3

以下是bizcoder.com的一些选项

使用HttpResponseMessage

 [HttpPost()] [Route("PostLog")] public async Task PostLog(HttpRequestMessage request) { var jsonString = await request.Content.ReadAsStringAsync(); _LogService.PostLog(jsonString); } 

或者使用json.net

 [HttpPost()] [Route("PostLog")] public void PostLog([FromBody]JToken jsonbody) { var jsonString = jsonbody.ToString(); _LogService.PostLog(jsonString); } 
  • SO – 如何发布单个字符串(使用表单编码)
  • SO – 发送单个字符串参数 – 这可能是更好的选择,很好的答案。