要實現React前端與C#后端的通信,您可以使用RESTful API或GraphQL。這里我們將介紹如何使用RESTful API實現通信。
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
[ApiController]
[Route("[controller]")]
public class UsersController : ControllerBase
{
private static List<string> users = new List<string> { "User1", "User2", "User3" };
[HttpGet]
public IActionResult GetUsers()
{
return Ok(users);
}
[HttpPost]
public IActionResult AddUser([FromBody] string user)
{
users.Add(user);
return CreatedAtAction(nameof(GetUser), new { id = users.Count - 1 }, user);
}
[HttpGet("{id}")]
public IActionResult GetUser(int id)
{
if (id >= 0 && id< users.Count)
{
return Ok(users[id]);
}
else
{
return NotFound();
}
}
}
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy("AllowAllOrigins", builder => builder.AllowAnyOrigin());
});
// ...
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseCors("AllowAllOrigins");
// ...
}
import React, { useEffect, useState } from 'react';
function App() {
const [users, setUsers] = useState([]);
useEffect(() => {
fetch('https://localhost:5001/users')
.then((response) => response.json())
.then((data) => setUsers(data));
}, []);
return (
<div>
<h1>Users</h1>
<ul>
{users.map((user, index) => (
<li key={index}>{user}</li>
))}
</ul>
</div>
);
}
export default App;
這只是一個簡單的示例,您可以根據需要擴展和自定義這些代碼。希望對您有所幫助!