【问题标题】:How to get data from database into a table (Angular 8, C#, WebApi)如何从数据库中获取数据到表中(Angular 8、C#、WebApi)
【发布时间】:2020-08-18 11:56:12
【问题描述】:

我正在尝试做一些相对简单的事情,但我对所有选项感到困惑,我需要你的帮助。

我正在尝试从数据库中检索信息,通过 API 将其传递并显示在我用 Angular 制作的表格中。 这个想法是将所有状态为 1 的生产力放入某个列表中。将列表返回给 Angular 并在表格中显示数据。

我知道有很多选择。诚然,我测试的所有示例都应该在 Angular 和 C# 项目中。但是每个项目都各不相同,没有一个例子与我的项目结构相匹配。

这就是我的代码:(我知道很多细节都丢失了,而且并不完美 所以我需要帮助)

messages.component.html

<table id="customers">
                    <tr>
                        <th>productivity num</th>
                        <th>user ID</th>
                        <th>amount</th>
                        <th>Special comments</th>
                        <th>Accept/reject</th>
                    </tr>
                    <tr *ngFor="let item of productivityList">
                        <td>{{item.ProductivyCode}}</td>
                        <td>{{item.UserCode}}</td>
                        <td>{{item.ProductivityNum}}</td>
                        <td>{{item.Cmment}}</td>
                        <td>
                            <div>
                                <button class="button is-success">accept</button>
                                <button class="button is-danger">reject</button>
                            </div>
                        </td>
                    </tr>
                </table>

messages.component.ts

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { UserService } from 'src/app/shared/services/user.service';
import { Productivity } from 'src/app/shared/models/productivity';

@Component({
  selector: 'app-messages',
  templateUrl: './messages.component.html',
  styleUrls: ['./messages.component.css']
})
export class MessagesComponent implements OnInit {

  constructor(private router: Router, private userservice: UserService) { }

  productivityList: Productivity[];

  ngOnInit():void {
   this.getProductivityRequest();
  }

  getProductivityRequest() {
    this.userservice.getProductivityRequest().subscribe((res) => {
      this.productivityList = res;
      if (res)
        console.log("ok")
    },
      err =>
        console.log("faild")
    );
  }

user.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http'
import { Observable, observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { User } from '../models/user.model';
import { Productivity } from '../models/productivity';
import { Time } from '@angular/common';
import { stringify } from 'querystring';
//import { read } from 'fs';



@Injectable({
  providedIn: 'root'
})
export class UserService {

  url: string = "https://localhost:44387/api/User/";
  productivityList: Productivity[];

  constructor(private http: HttpClient) { }

  getProductivityRequest() {
    return this.http.get(this.url+'getProductivityRequest');
}

UserController.cs //这是我的 C# 项目

using BL;
using DTO;
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 WebApiSystem.Controllers
{
    [EnableCors(origins: "http://localhost:4200", headers: "*", methods: "*", SupportsCredentials = true)]
    [RoutePrefix("api/User")]

    public class UserController : ApiController
    {
        [HttpGet]
        [Route("getProductivityRequest")]

        public IHttpActionResult GetProductivityRequest()
        {
            return Ok(UserService.GetProductivityRequest());
        }    

    }
}

UserService.cs

using DAL;
using DTO;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BL
{
    public class UserService
    {
        public static IQueryable<dynamic> GetProductivityRequest()
        {
            using (Model2 db = new Model2())
            {
                db.Configuration.ProxyCreationEnabled = false;
                db.Configuration.LazyLoadingEnabled = false;
                IQueryable<dynamic> PList = db.ProductivityTbl.Select();//I want to make a condition within the SELECT that only an object whose status 1 will enter the list
                return PList;
            }
        }

    }
}

我希望它足够清楚,也许你可以告诉我如何正确编写代码,如果有人有其他想法,比如返回 JSON 对象,我希望你能告诉我如何去做......谢谢!

【问题讨论】:

  • 似乎一切都是正确的,当你用邮递员测试它时你的 API 返回什么?
  • OK 简单检查,只需在组件中输出 http 调用的结果即可。你在“log”里没问题,输出“res”,你有什么收获吗?如果您不启动 Postman 并进行相同的 http 调用并检查响应对象是否有错误。
  • 好的,他给了我以下错误:从源 'localhost:4200' 访问 XMLHttpRequest 在 'localhost:44387/api/User/getProductivityRequest' 已被 CORS 策略阻止:没有 'Access-Control-Allow-Origin' 标头存在于请求的资源上。当我做另一个功能时,他也给了我这个问题。当时的问题是该属性没有很好地放置,但现在我不知道出了什么问题
  • 您好,您可以通过在 web api 中配置 Startup 类的 Configure() 方法中的行为来解决 CORS 问题...。添加为下面的答案以正确显示代码。

标签: c# angular asp.net-web-api


【解决方案1】:

要解决从 Angular 前端调用 web api 时出现的 CORS 错误,您可以在 web api 中的 Startup 类的 Configure() 方法中配置行为...

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment()) app.UseDeveloperExceptionPage();

        app.UseCors("AllowAll");

        app.UseStaticFiles();
        app.UseRouting();
        app.UseAuthentication();
        app.UseAuthorization();
    }

【讨论】:

  • 感谢您尝试帮助 Ben,我很感激...对于我的无知我很抱歉,我不确定我是否完全理解我应该在哪里编写该方法你建议。
  • 在一个web api项目中,你应该有一个名为Startup.cs的文件,它一般用于配置asp.net处理管道和注册服务以进行依赖注入。该文件将包含可能已经定义了 Configure() 方法的 Startup 类。您可能只需要添加“UseCors”行。
  • 我查过了,我没有这样的文件。
  • 我建议您使用 Visual Studio 向导创建一个新的 Web API 项目并查看生成的文件。您应该会在项目文件夹中的 Program.cs 旁边看到 Startup.cs。
  • 我试图打开一个新项目,但仍然没有看到上面的文件。我尝试手动添加但无法实现接口。
【解决方案2】:

我试图打开一个新项目,但仍然没有看到上面的文件。我尝试手动添加但无法实现接口(他要我实现一个全新的接口)文件中是否缺少某些代码?

StartUp.cs

using System;
using System.Threading.Tasks;
using Microsoft.Owin;
using Owin;

[assembly: OwinStartup(typeof(WebApiSystem.Startup1))]

namespace WebApiSystem
{
    public class Startup1
    {
        public void Configuration(IAppBuilder app)
        {
            // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=316888
        }
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment()) app.UseDeveloperExceptionPage();

            app.UseCors("AllowAll");

            app.UseStaticFiles();
            app.UseRouting();
            app.UseAuthentication();
            app.UseAuthorization();
        }
    }
}

【讨论】:

    猜你喜欢
    • 2023-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-23
    • 1970-01-01
    • 1970-01-01
    • 2019-05-10
    相关资源
    最近更新 更多