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

问题描述 投票:0回答:1

请帮助!!我开始哭泣。

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

我将config.EnableCors()放入WebAPiConfig.csconfig.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);
      })
    );
  }

}

当我启动角度时,我可以通过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-urlencode编码时,两个代码都获得“空”值。而且我放了一个调试停止点

Insert stringInsert Object

非常感谢您的帮助!

angular cors http-post asp.net-web-api2
1个回答
0
投票

在您的:

export class IdeaModel {
    Label:string;
}

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

当然,如果您不故意更改它,则为它。

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

祝你好运:)

© www.soinside.com 2019 - 2024. All rights reserved.