找不到Angular2 POST Web api 404

时间:2016-10-06 19:55:20

标签: c# angular asp.net-web-api

我正在构建一个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>
 <Message>
      No HTTP resource was found that matches the request URI
  'http://localhost:3304/WebAPI/api/Log/PostLog/'.
 </Message>
 <MessageDetail>
      No action was found on the controller 'Log' that matches the request.
 </MessageDetail>
</Error>

任何人都可以帮我吗?我不明白为什么它会这样表现。

1 个答案:

答案 0 :(得分:6)

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

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

c#c​​ode

[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 answer将其字符串化为对象。

c#c​​ode

[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);
}