【发布时间】:2017-05-29 09:57:24
【问题描述】:
我在 Angular&C# 上的项目有问题。我是一个初学者,我有这个问题。当我将 json 从 angular 发送到 C# (POST) 时,虽然 json 具有值,但 c# 没有得到任何东西(int 的值为 0,字符串的值为 null)。我不知道我做错了什么。 Json 有这样的结构:
[{"delegacion":11,"municipio":1,"ejercicio":2017,"ninterno":-1,"tipo":"T"}]
我的代码
角度
preparaTarea(){
this.data.push({'delegacion':this.delegacion,
'municipio':this.municipio,
'ejercicio':this.ejercicio,
'ninterno':this.ninterno,
'tipo':this.tipo_producto});
this._DelegationService.sendPtipo(this.data)
.subscribe(res=>{
this.data = res;
},
(err) =>console.log(err));
}
sendPtipo(data){
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
let urlPtipo ='http://localhost:50790/ApiProductoTipo/CalculaPTRecinto';
let body = JSON.stringify(data);
console.log(body);
return this._http.post(urlPtipo , body , options)
.map(data => {alert('ok');})
.catch(this.handleError);
}
private handleError(error: Response) {
console.error(error);
return Observable.throw(error.json().error || 'Server error');
}}
c#
public class MyObj
{
public int delegacion { get; set; }
public int municipio { get; set; }
public int ejercicio { get; set; }
public int ninterno { get; set; }
public string tipo { get; set; }
}
[HttpPost]
[Route("~/ApiProductoTipo/CalculaPTRecinto")]
public HttpResponseMessage CalculaPTRecinto([FromBody]MyObj data)
{
var delegacion = data.delegacion;
var municipio = data.municipio;
var recinto = data.ninterno;
var ejercicio = data.ejercicio;
var tipo = data.tipo;
if (this.productoTipoService.CalculaPTRecinto(delegacion, municipio, recinto, ejercicio, tipo) != 0)
{
return Request.CreateResponse(HttpStatusCode.OK);
}
else
{
return Request.CreateResponse(HttpStatusCode.BadRequest);
}
}
当我调试时,delegacion、municipio 等的值为 0,tipo 为 null。有任何想法吗?非常感谢!
【问题讨论】:
-
尝试通过关注属性的顺序来发布硬代码数据,并检查您不应该发布数组
-
如果您先使用 Postman 或 fiddler 检查您的休息端点,然后在成功检查后继续使用硬编码对象,然后在您的代码中,这会更好