简体   繁体   English

Angular7 - .NET Core v2 抛出 http 415(不支持的媒体类型)

[英]Angular7 - .NET Core v2 throws http 415 (Unsupported Media Type)

I am trying to send the user's filled form as json to my api.我正在尝试将用户填写的表单作为 json 发送到我的 api。 But because it is not Json (I think) it returns this error in the console of my browser:但是因为它不是 Json(我认为)它在我的浏览器的控制台中返回这个错误:

415 (Unsupported Media Type) 415(不支持的媒体类型)

I have enabled CORS in my backend and also I am receiving json [FromBody] and I am pretty sure that the problem is from the angular code.我在后端启用了 CORS,并且我收到了 json [FromBody] ,我很确定问题出在角度代码上。

This is my form:这是我的表格:

<form [formGroup]="messageForm" (ngSubmit)="onSubmit(messageForm)" class="form-inline mt-2 mt-md-0">
      <h5 *ngIf="success"></h5>
        <input type="text" formControlName="Words" class="form-control mr-sm-2"  placeholder="test" aria-label="Words">
        <div *ngIf="submitted && messageForm.controls.Words.errors" class="error">
          <div *ngIf="messageForm.controls.Words.errors.required">test</div>
        </div>
      <button type="submit" value="Send message" class="btn btn-outline-success my-2 my-sm-0">test</button>
    </form>

This is my service class:这是我的服务类:

import { Component, OnInit } from '@angular/core';
import { DataService } from '../data.service';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
  messageForm: FormGroup;
  submitted = false;
  success = false;
  logsList;

  constructor(private data: DataService , private formBuilder: FormBuilder ) { }

  ngOnInit()  {
    this.messageForm = this.formBuilder.group({
      Words: ['', Validators.required]
    });
    }
    onSubmit(messageForm) {
      this.submitted = true;
      this.data.search(this.messageForm.value)
      .subscribe(dat=> {console.log(dat)})

      if (this.messageForm.invalid) {
        return;
      }

      this.success = true;

    }

and this is my data service:这是我的数据服务:

import { Injectable } from '@angular/core';
import { HttpClient, HttpErrorResponse, HttpHeaders } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class DataService {
  logsList;
  baseUrl = 'http://localhost:5000/Logs'

  constructor(private http: HttpClient) { }
  search(words: String) {

    var body = JSON.stringify(words);
    const headers = new HttpHeaders();
    headers.set('Content-Type', 'application/json; charset=utf-8');
    console.log(body)
    console.log(headers)
    return this.http.post(this.baseUrl + '/Search', body , {headers: headers})
  }
}

A simple string is already valid JSON.一个简单的string已经是有效的 JSON。 Since you are using a String object, you can simple set the body as the actual string value :由于您使用的是String对象,您可以简单地将正文设置为实际的字符串值:

let body = words.toString(); // or simply : let body = words; it should work as well IMHO

As a side note, I'd recommend using simply string as the type for words , instead of String .作为旁注,我建议使用简单的string作为words的类型,而不是String

This latter is supposed to be fancy wrapper around string (in C# however, string is an alias for String and so they are equivalent, though it's still recommended to use the alias lower-case version as well).后者被认为是看中周围的包装string (但在C#中, string是一个别名String ,所以他们是等价的,但它仍然建议使用别名小写形式为好)。

What happened ?发生了什么?

Without seeing actual data it can be only speculation.没有看到实际数据,只能是猜测。 I can't tell if it is the root of the problem, but doing a JSON.stringify on a string will end you sending double-double quoted string as the body of of your HTTP POST, which is maybe why your C# backend is not happy with it.我不知道这是否是问题的根源,但是对字符串执行JSON.stringify会结束您发送双双引号字符串作为 HTTP POST 的正文,这可能就是为什么您的 C# 后端不是很高兴。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 ASP.NET 核心 WebAPI:不支持的媒体类型 - HTTP 415 - ASP.NET Core WebAPI: Unsupported Media Type - HTTP 415 Angular 7 和 .NET Core API 中不支持的媒体类型 415 错误 - Unsupported Media Type 415 Error in Angular 7 & .NET Core API Angular 415 不支持的媒体类型 - Angular 415 Unsupported Media Type ASP.NET 核心表单 POST 结果为 HTTP 415 Unsupported Media Type 响应 - ASP.NET Core form POST results in a HTTP 415 Unsupported Media Type response .NET Core API 中的 Twilio StatusCallBack &amp; Gather POST 方法返回 HTTP 415 - 不支持的媒体类型 - Twilio StatusCallBack & Gather POST method in .NET Core API returning HTTP 415 - Unsupported Media Type 415 不支持的媒体类型 asp.net 核心 - 415 Unsupported Media Type asp.net core .net核心Web API-415不支持的媒体类型 - .net core Web API - 415 Unsupported Media Type 415(不支持的媒体类型) Angular API 调用 - 415 (Unsupported Media Type) Angular API call ASP.NET Core 中内容类型“application/csp-report”的“415 Unsupported Media Type” - "415 Unsupported Media Type" for Content-Type "application/csp-report" in ASP.NET Core 将整数列表发送到 REST API 会抛出 415(不支持的媒体类型) - Sending list of integers to REST API throws 415 (Unsupported Media Type)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM