溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶(hù)服務(wù)條款》

C# AJAX與前端Angular的集成實(shí)踐

發(fā)布時(shí)間:2024-09-09 15:38:14 來(lái)源:億速云 閱讀:80 作者:小樊 欄目:編程語(yǔ)言

在這個(gè)實(shí)踐中,我們將使用C#作為后端服務(wù)器端語(yǔ)言,AJAX進(jìn)行異步通信,以及Angular作為前端框架。我們將創(chuàng)建一個(gè)簡(jiǎn)單的應(yīng)用程序,該應(yīng)用程序可以從服務(wù)器獲取數(shù)據(jù)并在前端顯示。

  1. 創(chuàng)建C# Web API項(xiàng)目 首先,我們需要?jiǎng)?chuàng)建一個(gè)C# Web API項(xiàng)目。在Visual Studio中,選擇 “File” > “New” > “Project”,然后選擇 “ASP.NET Web Application (.NET Framework)”。給項(xiàng)目命名,例如 “MyWebAPI”,然后點(diǎn)擊 “OK”。

  2. 添加一個(gè)API控制器 在解決方案資源管理器中,右鍵單擊 “Controllers” 文件夾,然后選擇 “Add” > “Controller”。選擇 “Web API 2 Controller - Empty”,然后點(diǎn)擊 “Add”。給控制器命名,例如 “DataController”。

  3. 在DataController中添加一個(gè)GET方法,用于返回?cái)?shù)據(jù)。例如:

using System.Collections.Generic;
using System.Web.Http;

namespace MyWebAPI.Controllers
{
    public class DataController : ApiController
    {
        [HttpGet]
        public IHttpActionResult GetData()
        {
            var data = new List<string>
            {
                "Hello",
                "from",
                "the",
                "server"
            };
            return Ok(data);
        }
    }
}
  1. 配置CORS 在WebApiConfig.cs文件中,啟用CORS(跨域資源共享)以允許來(lái)自不同域的請(qǐng)求。在Register方法中添加以下代碼:
using System.Web.Http;

namespace MyWebAPI
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services
            var cors = new System.Web.Http.Cors.EnableCorsAttribute("*", "*", "*");
            config.EnableCors(cors);

            // Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }
}
  1. 創(chuàng)建Angular前端項(xiàng)目 使用Angular CLI創(chuàng)建一個(gè)新的Angular項(xiàng)目。在命令提示符中,運(yùn)行以下命令:
npm install -g @angular/cli
ng new my-angular-app
cd my-angular-app
  1. 安裝CORS代理 在Angular項(xiàng)目中,我們需要一個(gè)CORS代理來(lái)繞過(guò)瀏覽器的同源策略。在命令提示符中,運(yùn)行以下命令:
npm install cors-anywhere --save
  1. 配置代理 在Angular項(xiàng)目的根目錄下,創(chuàng)建一個(gè)名為 “proxy.conf.json” 的文件,并添加以下內(nèi)容:
{
  "/api": {
    "target": "http://localhost:5000",
    "secure": false,
    "changeOrigin": true,
    "logLevel": "debug"
  }
}

在 “package.json” 文件中,將 “start” 腳本更改為:

"scripts": {
  "start": "ng serve --proxy-config proxy.conf.json",
  ...
},
  1. 創(chuàng)建一個(gè)服務(wù) 在Angular項(xiàng)目中,創(chuàng)建一個(gè)名為 “data.service.ts” 的服務(wù),用于處理與后端的通信。在命令提示符中,運(yùn)行以下命令:
ng generate service data

編輯 “data.service.ts” 文件,添加以下內(nèi)容:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';

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

  constructor(private http: HttpClient) { }

  getData(): Observable<string[]> {
    return this.http.get<string[]>('/api/data');
  }
}
  1. 在組件中使用服務(wù) 在 “app.component.ts” 文件中,使用 “DataService” 獲取數(shù)據(jù)并將其顯示在視圖上。修改 “app.component.ts” 文件,添加以下內(nèi)容:
import { Component } from '@angular/core';
import { DataService } from './data.service';

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

  constructor(private dataService: DataService) {
    this.getData();
  }

  getData() {
    this.dataService.getData().subscribe(response => {
      this.data = response;
    });
  }
}
  1. 在視圖中顯示數(shù)據(jù) 在 “app.component.html” 文件中,使用 “data” 變量顯示從服務(wù)器獲取的數(shù)據(jù)。修改 “app.component.html” 文件,添加以下內(nèi)容:
<div style="text-align:center">
  <h1>
    Welcome to {{ title }}!
  </h1>
  <ul *ngIf="data">
    <li *ngFor="let item of data">{{ item }}</li>
  </ul>
</div>
  1. 運(yùn)行項(xiàng)目 首先,確保C# Web API項(xiàng)目正在運(yùn)行。然后,在Angular項(xiàng)目的命令提示符中,運(yùn)行以下命令:
ng serve

現(xiàn)在,打開(kāi)瀏覽器并導(dǎo)航到 “http://localhost:4200”。你應(yīng)該能看到從服務(wù)器獲取的數(shù)據(jù)。

這就是C# AJAX與前端Angular的集成實(shí)踐。在這個(gè)示例中,我們創(chuàng)建了一個(gè)簡(jiǎn)單的應(yīng)用程序,該應(yīng)用程序從C# Web API服務(wù)器獲取數(shù)據(jù)并在Angular前端顯示。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI