当前位置: 首页 > 知识库问答 >
问题:

Angular/ASP.NET Web API-Post字符串或对象-->错误请求

李泓
2023-03-14

请救命!!我开始哭了。

我想用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; }
}

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

    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时,我可以通过浏览器debug中的getMethod方法获得这个想法

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


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”。我放了一个调试停止点

插入字符串插入对象

非常感谢你的帮助!

共有1个答案

哈烨熠
2023-03-14

在您的:

export class IdeaModel {
    Label:string;
}

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

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

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

祝你好运:)

 类似资料:
  • 我是新来的。我正在创建注册功能,但当我发布请求时,它给我的错误是:“发布有效请求”。请你检查一下我的代码,告诉我我做错了什么。 服务 注册组件 注册HTML 用户界面

  • 我在Excel中的VBA宏中使用了以下代码: 在即时窗口中,我收到了以下错误: 400 Apache Tomcat/8.0.28-错误报告1{font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:22px;}H2{font-family:Tahoma,Arial,sans-serif;颜

  • 我正在学习python,当我在做这个练习的时候...

  • 问题内容: 我已经阅读了多篇有关此错误的文章,但仍然无法弄清。当我尝试遍历我的函数时: 这是错误: 问题答案: 如您在评论中所述,某些值似乎是浮点数,而不是字符串。您需要先将其更改为字符串,然后再传递给。最简单的方法是使用时更改为。无论如何,这样做已经没有什么害处,即使它已经是。

  • 我已经读了很多关于这个错误的帖子,但我仍然无法理解。当我尝试循环遍历我的函数时: 以下是错误:

  • 我想解析一些JSON,但一个键要么是字符串,要么是对象。 这是我当前的结构:https://github.com/PhillippOhlandt/pmtoapib/blob/master/CollectionItemRequest.go#L10 在这里,“Url”属性不仅可以是字符串,还可以是对象。 我开始为它创建一个自己的结构,覆盖对象案例。 但是这样字符串版本就不行了。有没有一种方法既能处理这