C# 創建可跨域訪問的 RESTful 服務(Web API)


1. 創建項目

  • VSCode 打開准備用來存放項目文件夾的文件夾;
  • VSCode 中打開終端,運行命令:
    dotnet new webapi -o HelloRestful

2. 添加自定義邏輯

  • 在解決方案中(Controllers 同級)新建一個 Models 文件夾;
  • 在 Models 目錄下新建 EmployeeInfo.cs 類,代碼如下:
    using System; namespace HelloRestful.Controllers { public class EmployeeInfo { public int EmployeeNo { get; set; } public string EmployeeName { get; set; } public int Age { get; set; } public int Sex { get; set; } public string Position { get; set; } public bool IsActive { get; set; } = false; public DateTime CreateDate { get; set; } = DateTime.Now; } }
    View Code
  • 當對話框詢問是否要將所需資產添加到項目時,選擇“是”。
  • 在 Controllers 目錄下新建 EmployeeInfoController.cs 類,代碼如下:
    using System.Collections.Generic; using Microsoft.AspNetCore.Mvc; namespace HelloRestful.Controllers { [Route("api/[controller]")] [ApiController] public class EmployeeInfoController { private List<EmployeeInfo> employeeInfos = new List<EmployeeInfo> { new EmployeeInfo{ EmployeeNo = 1, EmployeeName = "Jack", Age = 21, Sex = 1, Position = "Front-end Development", }, new EmployeeInfo{ EmployeeNo = 2, EmployeeName = "Tom", Age = 23, Sex = 0, Position = "Front-end Development", }, new EmployeeInfo{ EmployeeNo = 3, EmployeeName = "Martin", Age = 22, Sex = 1, Position = ".Net Development", }, }; [HttpGet] public IEnumerable<EmployeeInfo> Get() { return employeeInfos; } } }
    View Code

3. 配置 IP 地址和 端口號

  • 打開 Properties/launchSettings.json 文件;
  • 在下圖所示處修改 IP 地址和 端口號:

4. 添加允許跨域配置

  • 打開 Startup.cs 文件;
  • 在 Startup 類中,添加如下變量(位置無所謂,推薦放在構造函數 Startup() ):
    readonly string AllowRequestOrigins = "_allowRequestOrigins";
  • Startup 類的 ConfigureServices() 方法中添加允許訪問的域,代碼如下:
    services.AddCors(options =>
                {
                    options.AddPolicy(AllowRequestOrigins, builder =>
                    {
                        // 允許訪問的域,可添加多個
                        builder.WithOrigins("http://localhost:9080").AllowAnyHeader().AllowAnyMethod();
                    });
                });
    View Code
  • Startup 類的 Configure() 方法的 app.UseRouting(); 和 app.UseEndpoints(); 之間添加代碼如下:
    app.UseCors(AllowRequestOrigins);

5. 運行服務,並測試能否正確輸出數據

  • VSCode 終端中運行命令:
    cd HelloRestful
    dotnet run

   回車,輸出如下如所示:

   

  • 打開瀏覽器輸入:http://172.22.113.93:10001/api/EmployeeInfo 顯示如下:

  

 

 

 

 

 

 

參考:教程:使用 ASP.NET Core 創建 Web API

   .Net Core5 WebAPI + Vue + Axios 搭建一個跨域訪問的例子

   無法在 macOS 上啟動 ASP.NET Core gRPC 應用

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM