在ASP.NET Core 6中,可以通过分离单页应用(SPA)和API项目来实现更好的代码模块化和可维护性。下面是实现方法:
2.添加用于处理API请求的控制器,例如:
[ApiController]
[Route("api/[controller]")]
public class MyController : ControllerBase
{
[HttpGet]
public ActionResult Get()
{
return "Hello from API!";
}
}
创建一个新的SPA项目。我们可以使用不同的框架或库,例如Angular、React或Vue.js。
将SPA项目与API项目连接起来。在SPA项目中,通过HTTP请求调用API项目。例如:
async function callApi() {
const response = await fetch("/api/my");
const body = await response.text();
console.log(body);
}
根据需要配置和运行API和SPA项目。我们可以使用Visual Studio或命令行来构建、运行和调试这些项目。
注意:如果需要在同一个设备上运行API和SPA项目,需要使用不同的端口号。例如,API项目可以在5000端口上运行,而SPA项目可以在3000端口上运行。在这种情况下,可以使用代理或跨域请求来访问API。