【问题标题】:angular 6 post **array data** using `httpClient` method is not working with asp.net core APIangular 6 post **array data** using `httpClient`方法不适用于asp.net核心API
【发布时间】:2019-08-03 16:52:00
【问题描述】:

我对 dot-net 和 angular 技术比较陌生,并且正在尝试使用 angular-6 httpClient 方法发布 array 数据,但我未能点击 HTTP Post API方法(使用断点找到)。请帮我找出错误所在。

组件方法调用服务

let selectedLanguageList: userChoosenQC[] = [];

this.quizzerService.InsertUserChoosenDetails(selectedLanguageList)
.subscribe((data) => {});

调用API的服务类方法

InsertUserChoosenDetails(data: userChoosenQC[]): any {
     const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json' }) };
var details = this.httpClient.post<userChoosenQC[]>(this.apiUrl + '/Questions/InsertUserLikes',
     data, httpOptions);
    return details;}

userChoosenQC接口类型

export interface userChoosenQC{
      Id :number
     QuizType :number; 
     QuizzerDetails :number 
     QuizQuestions:number; 
     QuizChoices :number; 
}

我未能点击此 HTTP-POST API 方法

[HttpPost, Route("InsertUserLikes")]
        public ActionResult InsertUserSelections(List<QuizzerQCdetails> userSelectedQC)
        {
            userRepository.InsertUserSelectedQC(userSelectedQC);


return Ok(new { res="data Inserted sucessfully" });
    }``

QuizzerQCdetailsPOCO类

public class QuizzerQCdetails
    {
        public int Id { get; set; }
        public QuizType quizType { get; set; }
        public QuizzerDetails quizzerDetails { get; set; }
        public QuizQuestions quizQuestions { get; set; }
        public QuizChoices quizChoices { get; set; }
    }

我收到了这个错误

HTTP/1.1 405 方法不允许”

【问题讨论】:

  • 你在服务器端看到了什么错误?
  • 我在服务器端没有看到任何错误 api 没有命中。
  • 你能分享任何代码 sn-ps 到 post list 或 array 使用 angular-6 和 asp.net api 核心的数据,这可能有助于理解我的代码错误
  • QuizTypeQuizzerDetails 等是什么?您正在传递带有数字属性的 userChoosenQC ,但您收到的模型似乎无关紧要。
  • 尝试在您的网络浏览器开发工具中与我们分享您的网络标签和错误。你的客户端和 web api 在同一个项目中吗?

标签: angular asp.net-core-2.0


【解决方案1】:

对于这个错误,它似乎是由于 cors 问题而失败的。尝试在 web api 中配置 CORS,例如

    services.AddCors(options =>
        {
            options.AddPolicy("CorsPolicy",
                builder => builder.WithOrigins("http://example.com")
                .AllowAnyMethod()
                .AllowAnyHeader()
                .AllowCredentials());
        });

app.UseCors();

另外,不确定你当前的Controller代码,尝试添加FromBody

    [HttpPost, Route("InsertUserLikes")]
    public ActionResult InsertUserSelections([FromBody]List<QuizzerQCdetails> userSelectedQC)

【讨论】:

    猜你喜欢
    • 2017-05-20
    • 2019-09-17
    • 1970-01-01
    • 2021-09-28
    • 2019-02-04
    • 1970-01-01
    • 2016-11-20
    • 2018-12-08
    • 1970-01-01
    相关资源
    最近更新 更多