繁体   English   中英

找不到Angular2 POST Web API 404

[英]Angular2 POST Web api 404 Not Found

我正在构建一个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>

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

这是因为您不能将原子值作为json直接发布到您的方法中。 您可以将其变成一个对象,然后将其发布为相应的对象,或者以uri编码形式发布,也可以使用。 这是asp.net的网络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);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM