![](/img/trans.png)
[英]Issue while binding the POSTed complex form data from Angular JS to ASP.Net Web API 2
[英]ASP.NET Web API does not receive the data posted from Angular
我目前正在嘗試將角度模型發布到 .NET Core MVC 中的 Web API。 Angular 側的模型在 Posts to the web API 點之前正確填充。 然而,當它到達 API 時,模型看起來像{"urlEndpoint":null,"token":null}
。
我嘗試更改標頭Content-Type
,我嘗試添加[FromBody]
,我還嘗試將控制器從HttpResponseMessage
更改為IHttpActionResult
- 實際上幾乎所有關於堆棧溢出的解決方案都適用於類似問題。 然而,有趣的是,同樣的代碼在標准 .NET 上的舊項目中也能工作。
對此的任何幫助將不勝感激......這讓我發瘋!
角度組件:
getPdfData() {
let token = this.httpService.getToken("token");
this.urlAndTokenModel = new UrlAndTokenModel();
this.urlAndTokenModel.Token = token;
this.urlAndTokenModel.UrlEndpoint = this.apiEndpoint;
this.httpService.postPdfBytes('/blahblah/api/pleaseworkthistime', this.urlAndTokenModel, this.successCallback.bind(this),
this.failureCallback.bind(this));
}
角 http.service
postPdfBytes(url: string, data: UrlAndTokenModel, successCallback, errorCallback) {
return this.http.post(url, data,
{
headers: new HttpHeaders().set('Content-Type', 'application/json'),
responseType: 'blob'
}
).subscribe(
resp => successCallback(resp),
error => errorCallback(error)
);
}
網絡API:
public class TestController : BaseController
{
public TestController(ICacheHelper cacheHelper) :
base(cacheHelper)
{
}
[Route("api/pleaseworkthistime")]
[HttpPost]
public HttpResponseMessage GetDocument(UrlAndTokenModel data)
{
var client = new HttpClient();
client.DefaultRequestHeaders.Add("Authorization", data.Token);
var responseTask = client.GetAsync(data.UrlEndpoint);
responseTask.Wait();
var result = responseTask.Result;
byte[] finalResult = null;
if (result.IsSuccessStatusCode)
{
var readTask = result.Content.ReadAsByteArrayAsync();
readTask.Wait();
finalResult = readTask.Result;
}
var httpRequestMessage = new HttpRequestMessage();
var httpResponseMessage = httpRequestMessage.CreateResponse(HttpStatusCode.OK);
httpResponseMessage.Content = new ByteArrayContent(finalResult);
httpResponseMessage.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
httpResponseMessage.Content.Headers.ContentDisposition.FileName = "mytestpdf.pdf";
httpResponseMessage.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream");
return httpResponseMessage;
}
}
然后顯然有帶有URLEndpoint
和令牌的角度URLAndTokenModel
- C# 模型中也有相同的鏡像。
終於解決了! 我希望這可以幫助其他人遇到同樣的問題。
當它發布到 .NET API 時,它首先需要是 JSON.Stringify
this.httpService.postPdfBytes('/blahblah/api/pleaseworkthistime', JSON.stringify(this.urlAndTokenModel), this.successCallback.bind(this),
this.failureCallback.bind(this));
因此,角度 http.service 也需要更新為字符串而不是模型。
postPdfBytes(url: string, data: string, successCallback, errorCallback)
此時它仍然沒有它,然后簡單地將 [FromBody] 添加到 Controller 和 walahh!
public HttpResponseMessage GetDocument([FromBody] UrlAndTokenModel data)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.