溫馨提示×

React前端如何與C#后端通信

c#
小樊
82
2024-09-10 22:37:45
欄目: 編程語言

要實現(xiàn)React前端與C#后端的通信,您可以使用RESTful API或GraphQL。這里我們將介紹如何使用RESTful API實現(xiàn)通信。

  1. 創(chuàng)建C#后端API 首先,在C#后端中創(chuàng)建一個Web API。您可以使用ASP.NET Core來實現(xiàn)。以下是一個簡單的示例:
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();
        }
    }
}
  1. 配置CORS 為了讓React應用程序能夠訪問C#后端API,您需要在C#后端中配置CORS(跨源資源共享)。在ASP.NET Core中,可以使用以下代碼片段進行配置:
public void ConfigureServices(IServiceCollection services)
{
    services.AddCors(options =>
    {
        options.AddPolicy("AllowAllOrigins", builder => builder.AllowAnyOrigin());
    });

    // ...
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    app.UseCors("AllowAllOrigins");

    // ...
}
  1. 在React前端調用API 現(xiàn)在,您可以在React應用程序中使用Fetch API或其他庫(如Axios)調用C#后端API。以下是一個使用Fetch API獲取用戶列表的示例:
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;

這只是一個簡單的示例,您可以根據需要擴展和自定義這些代碼。希望對您有所幫助!

0