要实现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;
这只是一个简单的示例,您可以根据需要扩展和自定义这些代码。希望对您有所帮助!