Angular / ASP.Net Web API -- 发布字符串或对象 --> 错误请求

Posted

技术标签:

【中文标题】Angular / ASP.Net Web API -- 发布字符串或对象 --> 错误请求【英文标题】:Angular / ASP.Net Web API -- Post String or Object --> Bad Request 【发布时间】:2020-04-21 22:36:01 【问题描述】:

请帮忙!!我开始哭了。

我想用 Angular 和 ASP.Net Web API 创建一个 Intranet 应用程序。 我可以从 API 获取数据,但无法将字符串/对象发布到 Web Api。 我创建了我的 WebApi:

我把 config.EnableCors() 放在 WebAPiConfig.cs config.EnableCors()

我创建了一个模型类“Idea”:

 public class Idea

    public string Label  get; set; 

我为“创意”创建了一个控制器

    using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Cors;

namespace WebApplication1.Controllers

    [EnableCors(origins: "http://localhost:4200", headers: "*", methods: "*")]
    [RoutePrefix("Api/Idea")]
    public class IdeaController : ApiController
    

        [HttpGet]
        [Route("getIdeas")]
        public List<Models.Idea> GetIdees()
        
            List<Models.Idea> List_Ideas = new List<Models.Idea>();



            Models.Idea myIdea = new Models.Idea();

            myIdea.Label = "This works!";

            List_Ideas.Add(myIdea);


            return (List_Ideas);
        


        [HttpPost]
        [Route("InsertIdeaString")]
        public IHttpActionResult PostIdeaString([FromBody] string Label)
        

            return Ok(Label);
        

        [HttpPost]
        [Route("InsertIdeaObject")]
        public IHttpActionResult PostIdeaObject([FromBody] Models.Idea myIdea)
        

            return Ok(myIdea.Label);
        

    

在我的 Angular 应用程序中,我创建了一个服务,一个模型:

    import  Injectable  from '@angular/core';
    import   IdeaModel  from '../Model/idea-model';
    import  HttpClient, HttpHeaders, HttpParams   from '@angular/common/http';
    import  Observable  from 'rxjs';

@Injectable(
  providedIn: 'root'
)
export class IdeaServiceService 

  url = 'http://localhost:52133/Api/Idea';  

  constructor(private http: HttpClient)  


  getIdees(): Observable<IdeaModel[]>   
    return this.http.get<IdeaModel[]>(this.url + '/getIdeas',  
      headers:  
    );  
    



  createIdea_Object(idea: IdeaModel): Observable<void>   

    const config = new HttpHeaders().set('Content-Type', 'application/json');
    return this.http.post<void>(this.url + '/InsertIdeaObject', JSON.stringify(idea),  headers: config );
    


  createIdea_String(idea: string): Observable<void>   

    const httpOptions =  headers: "content-type" : "text/html" ;  
    return this.http.post<void>(this.url + '/InsertIdeaString', idea, httpOptions);  
    



我创建了模型:

    export class IdeaModel 
    Label:string;

在 App.component.html 中:

<button type="button" class="btn btn-secondary"  (click)="create_from_object()"  >Click create object idea </button>
<button type="button" class="btn btn-secondary"  (click)="create_from_string()"  >Click create string idea </button>

<router-outlet></router-outlet>

在 App.component.ts 中:

import  Component  from '@angular/core';
import  IdeaModel   from './Model/idea-model';
import  IdeaServiceService  from  './Service/idea-service.service';


@Component(
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
)
export class AppComponent 
  title = 'angular';

  constructor(private IdeaServiceService: IdeaServiceService)  


  ngOnInit() 
    this.IdeaServiceService.getIdees().subscribe(
     (res=> 
        console.log(res);
      )
    );





  create_from_object():void
  
    let myIdea:IdeaModel = new IdeaModel;
    myIdea.Label="this works?!";


    this.IdeaServiceService.createIdea_Object(myIdea).subscribe(
      (res=> 
      console.log(res);
      )
    );
  





  create_from_string():void
  

    let myString: string="this works?!";

    this.IdeaServiceService.createIdea_String(myString).subscribe(
      (res=> 
      console.log(res);
      )
    );
  


当我启动 Angular 时,我可以通过 get 方法获取 Idea: getMethod in browser debug

但是,我不能发布字符串或对象,当我点击按钮时,我收到了一个错误的请求:


zone-evergreen.js:2952 OPTIONS http://localhost:52133/Api/Idea/InsertIdeaObject 400 (Bad Request)
scheduleTask @ zone-evergreen.js:2952
scheduleTask @ zone-evergreen.js:378
onScheduleTask @ zone-evergreen.js:272
scheduleTask @ zone-evergreen.js:372
scheduleTask @ zone-evergreen.js:211
scheduleMacroTask @ zone-evergreen.js:234
scheduleMacroTaskWithCurrentZone @ zone-evergreen.js:1107
(anonymous) @ zone-evergreen.js:2985
proto.<computed> @ zone-evergreen.js:1428
(anonymous) @ http.js:2581
_trySubscribe @ Observable.js:42
subscribe @ Observable.js:28
(anonymous) @ subscribeTo.js:20
subscribeToResult @ subscribeToResult.js:7
_innerSub @ mergeMap.js:59
_tryNext @ mergeMap.js:53
_next @ mergeMap.js:36
next @ Subscriber.js:49
(anonymous) @ scalar.js:4
_trySubscribe @ Observable.js:42
subscribe @ Observable.js:28
call @ mergeMap.js:21
subscribe @ Observable.js:23
call @ filter.js:13
subscribe @ Observable.js:23
call @ map.js:16
subscribe @ Observable.js:23
create_from_object @ app.component.ts:34
eval @ AppComponent.html:1
handleEvent @ core.js:43993
callWithDebugContext @ core.js:45632
debugHandleEvent @ core.js:45247
dispatchEvent @ core.js:29804
(anonymous) @ core.js:42925
(anonymous) @ platform-browser.js:2668
invokeTask @ zone-evergreen.js:391
onInvokeTask @ core.js:39680
invokeTask @ zone-evergreen.js:390
runTask @ zone-evergreen.js:168
invokeTask @ zone-evergreen.js:465
invokeTask @ zone-evergreen.js:1603
globalZoneAwareCallback @ zone-evergreen.js:1629
Show 12 more frames
localhost/:1 Access to XMLHttpRequest at 'http://localhost:52133/Api/Idea/InsertIdeaObject' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
core.js:6014 ERROR HttpErrorResponse headers: HttpHeaders, status: 0, statusText: "Unknown Error", url: "http://localhost:52133/Api/Idea/InsertIdeaObject", ok: false, …
OPTIONS http://localhost:52133/Api/Idea/InsertIdeaString 400 (Bad Request)
scheduleTask @ zone-evergreen.js:2952
scheduleTask @ zone-evergreen.js:378
onScheduleTask @ zone-evergreen.js:272
scheduleTask @ zone-evergreen.js:372
scheduleTask @ zone-evergreen.js:211
scheduleMacroTask @ zone-evergreen.js:234
scheduleMacroTaskWithCurrentZone @ zone-evergreen.js:1107
(anonymous) @ zone-evergreen.js:2985
proto.<computed> @ zone-evergreen.js:1428
(anonymous) @ http.js:2581
_trySubscribe @ Observable.js:42
subscribe @ Observable.js:28
(anonymous) @ subscribeTo.js:20
subscribeToResult @ subscribeToResult.js:7
_innerSub @ mergeMap.js:59
_tryNext @ mergeMap.js:53
_next @ mergeMap.js:36
next @ Subscriber.js:49
(anonymous) @ scalar.js:4
_trySubscribe @ Observable.js:42
subscribe @ Observable.js:28
call @ mergeMap.js:21
subscribe @ Observable.js:23
call @ filter.js:13
subscribe @ Observable.js:23
call @ map.js:16
subscribe @ Observable.js:23
create_from_string @ app.component.ts:50
eval @ AppComponent.html:2
handleEvent @ core.js:43993
callWithDebugContext @ core.js:45632
debugHandleEvent @ core.js:45247
dispatchEvent @ core.js:29804
(anonymous) @ core.js:42925
(anonymous) @ platform-browser.js:2668
invokeTask @ zone-evergreen.js:391
onInvokeTask @ core.js:39680
invokeTask @ zone-evergreen.js:390
runTask @ zone-evergreen.js:168
invokeTask @ zone-evergreen.js:465
invokeTask @ zone-evergreen.js:1603
globalZoneAwareCallback @ zone-evergreen.js:1629
Show 12 more frames
localhost/:1 Access to XMLHttpRequest at 'http://localhost:52133/Api/Idea/InsertIdeaString' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

我测试了很多代码,并且在内容类型中使用 application/x-www-form-urlencoded,我得到了两者的“null”值。我放了一个调试停止点

Insert string Insert Object

非常感谢您的帮助!

【问题讨论】:

【参考方案1】:

在你的:

export class IdeaModel 
    Label:string;

尝试将属性名称更改为“标签”(不要大写 L)。 这是 WebApi 期望接收(和发送)数据的默认方式。 请求和响应应该是 C# 属性的驼峰式版本。

这是,当然,如果你不故意改变它。

此外,在 POST 操作中,您不需要 [FromBody] 属性。它期望数据来自请求的正文。

祝你好运:)

【讨论】:

以上是关于Angular / ASP.Net Web API -- 发布字符串或对象 --> 错误请求的主要内容,如果未能解决你的问题,请参考以下文章

Angular / ASP.Net Web API -- 发布字符串或对象 --> 错误请求

Visual Studio 中带有 ASP.NET Web API 项目的 Angular 项目

ASP.NET 核心 Web API 和 Angular 客户端中的外部身份验证

使用ASP.NET Web API和Web API Client Gen使Angular 2应用程序的开发更加高效

带有asp.net Web API后端的Angular 2 Web应用程序的实时通知[关闭]

Angular2 HTTP Post ASP.NET MVC Web API