Angular Post 错误不正确 Content-Type: application/json
Angular Post Error Incorrect Content-Type: application/json
我正在使用 .Net Core web api 和 Angular 构建一个 POST 请求,我正在发送一个 json object上传文件到服务器。在 Postman 中一切正常,但是当我从 Angular 应用程序发出相同的请求时,出现以下错误。
System.InvalidOperationException: Incorrect Content-Type: application/json
我的 UI 代码...
``
// 显示 key/value 对
console.log(Object.entries(frmData));//returns 一个空数组!
var options = {content: frmData};
//submit this after the job id is returned
let httpOptions = {
headers: new HttpHeaders(
{
//'Content-Type': 'application/json',
'Content-Type': 'multipart/form-data',
'Referer': 'http://localhost:4200',
'Origin': 'http://localhost:4200',
//'Accept': 'application/json',
'Accept': '*/*',
'Authorization':'Bearer '+ this.loadToken()
}
).set('content-type','application/json').set('content-length','6')
};
this.httpService.post("http://localhost:63052/api/Document_ADD", options,httpOptions).subscribe(
data => {
debugger
console.log(data);
},
(err: HttpErrorResponse) => {
console.log(err.message); //Show error, if any
}
)
``
网页API
[HttpPost]
public async Task<IActionResult> InsertCustomer_Document_ADDResult([FromForm] Customer_Document_ADD customer_Document_ADDED)
{
var reqFile = Request.Form.Files.First();
using (Stream stream = reqFile.OpenReadStream())
{
using (var binaryReader = new BinaryReader(stream))
{
var fileContent = binaryReader.ReadBytes((int)stream.Length);
customer_Document_ADDED.file_data = fileContent;
var result = await _repository.InsertCustomer_Document_ADDResult(customer_Document_ADDED);
return Ok(result);
}
}
//return Ok(await _repository.InsertCustomer_Document_ADDResult(customer_Document_ADDED));
}
这是我的 headers 的屏幕截图。
更新 httpheader 后收到其他错误...
我在这里更新了 headers 以包含 responseType,但我仍然遇到相同的 Failed to read the request form
错误。
//submit this after the job id is returned
let httpOptions = {
headers: new HttpHeaders(
{
//'Content-Type': 'application/json',
'Content-Type': 'multipart/form-data',
'Referer': 'http://localhost:4200',
'Origin': 'http://localhost:4200',
'Accept': 'application/json',
//'Accept': '*/*',
'Authorization':'Bearer '+ this.loadToken()
}
),responseType: 'text' as 'text'
//.set('content-type','application/json').set('content-length','6')
};
this.httpService.post("http://localhost:63052/api/Customer_Document_ADD", options,httpOptions).subscribe(
data => {
debugger
console.log(data);
},
(err: HttpErrorResponse) => {
console.log(err.message); //Show error, if any
}
)
设置 'Content-Type': undefined
而不是 'Content-Type': 'multipart/form-data'
,可以防止请求完全发送到服务器!
已更新响应类型...
console.log(Object.entries(frmData));//returns an empty array!
var options = {content: frmData};
//submit this after the job id is returned
let httpOptions = {
headers: new HttpHeaders(
{
//'Content-Type': 'application/json',
'Content-Type': 'multipart/form-data',
// 'Content-Type': undefined,//this disables this request from being sent
'Referer': 'http://localhost:4200',
'Origin': 'http://localhost:4200',
'Accept': 'application/json',
//'Accept': '*/*',
'Authorization':'Bearer '+ this.loadToken()
}
),responseType: 'text' as const
//.set('content-type','application/json').set('content-length','6')
};
this.httpService.post("http://localhost:63052/api/Customer_Document_ADD", options,httpOptions).subscribe(
data => {
debugger
console.log(data);
},
(err: HttpErrorResponse) => {
console.log(err.message); //Show error, if any
}
)
Content-Type header 表示您在请求中“发送”的数据类型。
您最初将其设置为 'multipart/form-data' 但后来您将其覆盖为 application/json。
let httpOptions = {
headers: new HttpHeaders(
{
//'Content-Type': 'application/json',
'Content-Type': 'multipart/form-data',//here you set it to form data
'Referer': 'http://localhost:4200',
'Origin': 'http://localhost:4200',
//'Accept': 'application/json',
'Accept': '*/*',
'Authorization':'Bearer '+ this.loadToken()
}
).set('content-type','application/json').set('content-length','6')// here you overwrite it to application/json
}
您的端点需要表单数据,因为您在参数中使用了 [FromForm]。
您的屏幕截图显示发送的“application/json”不正确 header。
记住 Content-Type 表示您发送的内容,接受表示您期望返回的内容。
所以在这种情况下你的 Content-Type 应该是 'multipart/form-data' 如果你希望 json 回来你的接受应该是 'application/json'.
此外,如果你想从你的端点 return json 我通常喜欢 return ObjectResult 而不是像这样的 Ok:
return new ObjectResul(result);//this is better for returning json from an api endpoint. It will properly set the header in the response
我发现 returning ObjectResult 正确地设置了响应 headers。同样,作为一条小建议,最好始终从 json 端点 return 一些 class。
例如,我总是创建一个 class,例如:
public class DataResult<TResult>
{
public bool Success { get; set; }
public TResult Content { get; set; }
}
我所有的 api 端点 return class 这样我就可以用一种“标准”方式从我的 api 获得“响应”。
在这种情况下,伪代码如下所示:
[HttpPost]
public async Task<IActionResult> InsertCustomer_Document_ADDResult([FromForm] Customer_Document_ADD customer_Document_ADDED)
{
var reqFile = Request.Form.Files.First();
using (Stream stream = reqFile.OpenReadStream())
{
using (var binaryReader = new BinaryReader(stream))
{
var fileContent = binaryReader.ReadBytes((int)stream.Length);
customer_Document_ADDED.file_data = fileContent;
var result = await _repository.InsertCustomer_Document_ADDResult(customer_Document_ADDED);
//lets imagine that result is a strin but it can be anything
var dataResult = new DataResult<string> { Success = true, Content = result };
return new ObjectResult(dataResult);
}
}
}
最后,如果你所有的端点 return json 我会这样装饰我的控制器:
[ApiController]
[Produces("application/json")]//this also helps with the response headers
public class MyController: ControllerBase
{
//a bunch of cool endpoint here
}
我正在使用 .Net Core web api 和 Angular 构建一个 POST 请求,我正在发送一个 json object上传文件到服务器。在 Postman 中一切正常,但是当我从 Angular 应用程序发出相同的请求时,出现以下错误。
System.InvalidOperationException: Incorrect Content-Type: application/json
我的 UI 代码...
``
// 显示 key/value 对
console.log(Object.entries(frmData));//returns 一个空数组!
var options = {content: frmData};
//submit this after the job id is returned
let httpOptions = {
headers: new HttpHeaders(
{
//'Content-Type': 'application/json',
'Content-Type': 'multipart/form-data',
'Referer': 'http://localhost:4200',
'Origin': 'http://localhost:4200',
//'Accept': 'application/json',
'Accept': '*/*',
'Authorization':'Bearer '+ this.loadToken()
}
).set('content-type','application/json').set('content-length','6')
};
this.httpService.post("http://localhost:63052/api/Document_ADD", options,httpOptions).subscribe(
data => {
debugger
console.log(data);
},
(err: HttpErrorResponse) => {
console.log(err.message); //Show error, if any
}
)
``
网页API
[HttpPost]
public async Task<IActionResult> InsertCustomer_Document_ADDResult([FromForm] Customer_Document_ADD customer_Document_ADDED)
{
var reqFile = Request.Form.Files.First();
using (Stream stream = reqFile.OpenReadStream())
{
using (var binaryReader = new BinaryReader(stream))
{
var fileContent = binaryReader.ReadBytes((int)stream.Length);
customer_Document_ADDED.file_data = fileContent;
var result = await _repository.InsertCustomer_Document_ADDResult(customer_Document_ADDED);
return Ok(result);
}
}
//return Ok(await _repository.InsertCustomer_Document_ADDResult(customer_Document_ADDED));
}
这是我的 headers 的屏幕截图。
更新 httpheader 后收到其他错误...
我在这里更新了 headers 以包含 responseType,但我仍然遇到相同的 Failed to read the request form
错误。
//submit this after the job id is returned
let httpOptions = {
headers: new HttpHeaders(
{
//'Content-Type': 'application/json',
'Content-Type': 'multipart/form-data',
'Referer': 'http://localhost:4200',
'Origin': 'http://localhost:4200',
'Accept': 'application/json',
//'Accept': '*/*',
'Authorization':'Bearer '+ this.loadToken()
}
),responseType: 'text' as 'text'
//.set('content-type','application/json').set('content-length','6')
};
this.httpService.post("http://localhost:63052/api/Customer_Document_ADD", options,httpOptions).subscribe(
data => {
debugger
console.log(data);
},
(err: HttpErrorResponse) => {
console.log(err.message); //Show error, if any
}
)
设置 'Content-Type': undefined
而不是 'Content-Type': 'multipart/form-data'
,可以防止请求完全发送到服务器!
已更新响应类型...
console.log(Object.entries(frmData));//returns an empty array!
var options = {content: frmData};
//submit this after the job id is returned
let httpOptions = {
headers: new HttpHeaders(
{
//'Content-Type': 'application/json',
'Content-Type': 'multipart/form-data',
// 'Content-Type': undefined,//this disables this request from being sent
'Referer': 'http://localhost:4200',
'Origin': 'http://localhost:4200',
'Accept': 'application/json',
//'Accept': '*/*',
'Authorization':'Bearer '+ this.loadToken()
}
),responseType: 'text' as const
//.set('content-type','application/json').set('content-length','6')
};
this.httpService.post("http://localhost:63052/api/Customer_Document_ADD", options,httpOptions).subscribe(
data => {
debugger
console.log(data);
},
(err: HttpErrorResponse) => {
console.log(err.message); //Show error, if any
}
)
Content-Type header 表示您在请求中“发送”的数据类型。
您最初将其设置为 'multipart/form-data' 但后来您将其覆盖为 application/json。
let httpOptions = {
headers: new HttpHeaders(
{
//'Content-Type': 'application/json',
'Content-Type': 'multipart/form-data',//here you set it to form data
'Referer': 'http://localhost:4200',
'Origin': 'http://localhost:4200',
//'Accept': 'application/json',
'Accept': '*/*',
'Authorization':'Bearer '+ this.loadToken()
}
).set('content-type','application/json').set('content-length','6')// here you overwrite it to application/json
}
您的端点需要表单数据,因为您在参数中使用了 [FromForm]。
您的屏幕截图显示发送的“application/json”不正确 header。
记住 Content-Type 表示您发送的内容,接受表示您期望返回的内容。
所以在这种情况下你的 Content-Type 应该是 'multipart/form-data' 如果你希望 json 回来你的接受应该是 'application/json'.
此外,如果你想从你的端点 return json 我通常喜欢 return ObjectResult 而不是像这样的 Ok:
return new ObjectResul(result);//this is better for returning json from an api endpoint. It will properly set the header in the response
我发现 returning ObjectResult 正确地设置了响应 headers。同样,作为一条小建议,最好始终从 json 端点 return 一些 class。
例如,我总是创建一个 class,例如:
public class DataResult<TResult>
{
public bool Success { get; set; }
public TResult Content { get; set; }
}
我所有的 api 端点 return class 这样我就可以用一种“标准”方式从我的 api 获得“响应”。
在这种情况下,伪代码如下所示:
[HttpPost]
public async Task<IActionResult> InsertCustomer_Document_ADDResult([FromForm] Customer_Document_ADD customer_Document_ADDED)
{
var reqFile = Request.Form.Files.First();
using (Stream stream = reqFile.OpenReadStream())
{
using (var binaryReader = new BinaryReader(stream))
{
var fileContent = binaryReader.ReadBytes((int)stream.Length);
customer_Document_ADDED.file_data = fileContent;
var result = await _repository.InsertCustomer_Document_ADDResult(customer_Document_ADDED);
//lets imagine that result is a strin but it can be anything
var dataResult = new DataResult<string> { Success = true, Content = result };
return new ObjectResult(dataResult);
}
}
}
最后,如果你所有的端点 return json 我会这样装饰我的控制器:
[ApiController]
[Produces("application/json")]//this also helps with the response headers
public class MyController: ControllerBase
{
//a bunch of cool endpoint here
}