【发布时间】:2020-09-23 09:07:36
【问题描述】:
一个简单的请求,之前设法这样做,并认为我已经考虑了所有选项: 尝试向 web-api 控制器发布一个简单的请求。 从邮递员那里设法这样做,应用 enableCors,当将正文作为 null 并且没有 httpHeaders 作为选项时 - 设法到达控制器 REST 方法。 但是-当尝试发送正文接收 404 和 cors 错误时(不要认为这是正确的错误消息)。 查看我的代码(可能有错别字——手写,而不是复制+粘贴):
我的控制器:
[RoutePrefix("api/Data"]
public class DataController :ApiController
{
[Route("Get")]
public Object Get()//this is working
{
//do something
}
[Route("Update")]
[HttpPost]
public HttpResponseMessage Post ([FromBody] DataObject data)
{
return Request.CreateResponse(HttpStatusCode.OK, true);
}
}
数据模型:
public class DataObject
{
[JsonProperty("Prop1")]
public int Prop1 {get; set;}
[JsonProperty("Prop2")]
public string Prop2 {get; set;}
public DataObject(){}
}
客户端(角度): 客户端数据模型及调用函数:
export class ClientDataObject
{
public prpt1 :number;
public prpt2:string;
co structor(pr1:number, pr2 :string)
{
this.prpt1 =pr1;
this.prpt2 =pr2;
}
}
PostSomeData(property1:number, property2: string)
{
const httpOptions =
{
headers: new HttpHeaders({'Content-type''Application/json'})
}
let data: ClientDataObject=
{
Prop1:1,
Prop2: "test"
}
let data2: ClientDataObject =new ClientDataObject(1,"test");
//All the options I tried:
//This is working - null as body and no options
return this.httpClient.post<any>(<baseHref of the controller> + "Update", null/*,httpOptions*/);
return this.httpClient.post<any>(<baseHref of the controller> + "Update", data,httpOptions);
return this.httpClient.post<any>(<baseHref of the controller> + "Update", data); //without as httpOptions options
return this.httpClient.post<any>(<baseHref of the controller> + "Update",
{
'Prop1':1,
'Prop2': "test"
},httpOptions);
return this.httpClient.post<any>(<baseHref of the controller> + "Update", JSON.stringfy(data),httpOptions);
return this.httpClient.post<any>(<baseHref of the controller> + "Update", data2,httpOptions);
return this.httpClient.post<any>(<baseHref of the controller> + "Update", data2);
}
【问题讨论】:
标签: angular asp.net-web-api http-post