Nat*_*oss 0 c# asp.net-web-api angular
我正在构建一个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
}
}
Run Code Online (Sandbox Code Playgroud)
它调用一个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
Run Code Online (Sandbox Code Playgroud)
然而,当我的服务调用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>
Run Code Online (Sandbox Code Playgroud)
谁能帮我这个?我不明白为什么它会这样做.
因为你不能将原子值作为json直接发布到你的方法中.您可以将其转换为对象,然后将其作为相应对象发布,或者将其作为uri编码形式发布,也可以使用.这是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; }
}
Run Code Online (Sandbox Code Playgroud)
javascript代码
private convertToJSON(log: ILog): string {
return JSON.stringify({log: log});
}
Run Code Online (Sandbox Code Playgroud)
根据之前的SO答案将其字符串化为对象.
c#代码
[HttpPost()]
[Route("PostLog")]
public void PostLog([FromBody] string jsonString)
Run Code Online (Sandbox Code Playgroud)
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)});
}
Run Code Online (Sandbox Code Playgroud)
以下是bizcoder.com的一些选项
使用 HttpResponseMessage
[HttpPost()]
[Route("PostLog")]
public async Task PostLog(HttpRequestMessage request)
{
var jsonString = await request.Content.ReadAsStringAsync();
_LogService.PostLog(jsonString);
}
Run Code Online (Sandbox Code Playgroud)
或者使用 json.net
[HttpPost()]
[Route("PostLog")]
public void PostLog([FromBody]JToken jsonbody)
{
var jsonString = jsonbody.ToString();
_LogService.PostLog(jsonString);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1995 次 |
| 最近记录: |