Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/kubernetes/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
.net 角度Post错误不正确的内容类型:application/json_.net_Angular_Asp.net Core Webapi - Fatal编程技术网

.net 角度Post错误不正确的内容类型:application/json

.net 角度Post错误不正确的内容类型:application/json,.net,angular,asp.net-core-webapi,.net,Angular,Asp.net Core Webapi,我正在使用.NETCoreWebAPI和Angular构建一个POST请求,其中我将向服务器发送一个带有上传文件的json对象。在Postman中一切都很好,但是当我从Angular应用程序发出相同的请求时,我得到了以下错误。 System.invalidoOperationException:不正确的内容类型:应用程序/json 我的UI代码。。。 `` //显示键/值对 日志(Object.entries(frmData))//返回一个空数组! var options={content:fr

我正在使用.NETCoreWebAPI和Angular构建一个POST请求,其中我将向服务器发送一个带有上传文件的json对象。在Postman中一切都很好,但是当我从Angular应用程序发出相同的请求时,我得到了以下错误。
System.invalidoOperationException:不正确的内容类型:应用程序/json
我的UI代码。。。 `` //显示键/值对 日志(Object.entries(frmData))//返回一个空数组! 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
  }
)
``

Web 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));
    }
设置
'Content-Type':未定义的
而不是
'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
      }
    )

内容类型标头指示您在请求中“发送”的数据类型

您最初将其设置为“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”标题不正确

记住,内容类型告诉您正在发送什么,接受告诉您希望返回什么

因此,在这种情况下,您的内容类型应该是“multipart/formdata”,如果您希望返回json,那么您的Accept应该是“application/json”

另外,如果您希望从端点返回json,我通常希望返回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
[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);
        }
    }
}
[ApiController]
[Produces("application/json")]//this also helps with the response headers
public class MyController: ControllerBase
{
//a bunch of cool endpoint here
}
我发现返回ObjectResult可以正确设置响应头。还有一点建议,最好总是从json端点返回一些类

例如,我总是创建一个类,如:

public class DataResult<TResult>
{
    public bool Success { get; set; }
    public TResult Content { get; set; }
}

从这个角度看,您是在附加文件,然后将请求发布到服务器吗?您确实应该提供有关您尝试过的内容的附加信息。如果没有任何示例,我想这与Angular请求发送的标题有关,默认情况下,Angular将
application/json
作为内容类型发送。我更新了我的问题,以包含标题的屏幕截图。@carltonstith您的api会给您文本响应,因此,您还需要在post请求中设置
response:text
。另外,如果您有表单,那么您也可以使用formData,并将此表单数据传递给postrequest@carltonstith
'Content-Type':'multipart/form data')
您只需设置此项即可,然后更新UI代码,然后更新服务器代码。每次更改我都会收到以下错误
{“errors”:{“”:[“未能读取请求表单。缺少内容类型边界。”]},“type”:"https://tools.ietf.org/html/rfc7231#section-6.5.1、“标题”:“发生一个或多个验证错误”,“状态”:400,“traceId”:“6471eeca-47a2c60ff554f308.”
@carltonstith能否请您更新问题中的代码以反映这些更改,以便我可以查看代码并尝试复制。我很乐意帮助您进一步解决此问题。
[ApiController]
[Produces("application/json")]//this also helps with the response headers
public class MyController: ControllerBase
{
//a bunch of cool endpoint here
}