ASP.NET Core Web API 中控制器操作的返回类型及Swagger

ASP.NET Core Web API 中控制器操作的返回类型及Swagger


前言

👨‍💻👨‍🌾📝文章标题有些长,但是为了说清楚问题,只能啰嗦一点了。

本篇是ControllerBase中几个返回IActionResult接口或实现类(含子类)操作函数的学习与总结。期间使用的是Swagger测试了,发现Swagger还是需要一些设置的,顺带也记录一下。最后又学了一下跨域处理。


一、ControllerBase

ControllerBase中的处理函数比较多,本篇只是从函数的英文字面意思来看觉得很常见,所以挑出了几个研究一下。

ControllerBase文档:https://learn.microsoft.com/zh-cn/dotnet/api/microsoft.aspnetcore.mvc.controllerbase?view=aspnetcore-8.0

1.Content()

代码:

csharp 复制代码
/// <summary>
/// 测试Content()
/// </summary>
/// <param name="content">内容</param>
/// <returns>参数content</returns>
[HttpGet]
public IActionResult TestContent([FromQuery]string content)
{
    Debug.WriteLine(content);
    return Content(content);
}

Swagger效果:

可以看到HTTP 状态代码 200。

2.Forbid()

代码:

csharp 复制代码
/// <summary>
/// 测试Forbid()
/// </summary>
/// <returns></returns>
[HttpGet]
public IActionResult TestForbid()
{
    return Forbid();
}

Swagger效果:



可以看到HTTP 状态代码 500。

3.Ok()

代码:

csharp 复制代码
/// <summary>
/// 测试Ok()
/// </summary>
/// <param name="param">参数</param>
/// <returns></returns>
[HttpGet]
[Produces("application/json")]
public IActionResult TestOk([FromQuery] string param)
{
    Debug.WriteLine(param);
    return Ok(param);
}

Swagger效果:

可以看到HTTP 状态代码 200。

4.Problem()

代码:

csharp 复制代码
/// <summary>
/// 测试Problem()
/// </summary>
/// <param name="problem">问题</param>
/// <returns></returns>
[HttpPost]
public IActionResult TestProblem([FromBody] string problem)
{
    Debug.WriteLine(problem);
    return Problem(problem);
}

Swagger效果:




可以看到HTTP 状态代码 400。

5.NoContent()

代码:

csharp 复制代码
/// <summary>
/// 测试NoContent()
/// </summary>
/// <returns></returns>
[HttpGet]
public IActionResult TestNoContent()
{
    return NoContent();
}

Swagger效果:

可以看到HTTP 状态代码 204。

6.NotFound()

代码:

csharp 复制代码
/// <summary>
/// 测试NotFound()
/// </summary>
/// <returns></returns>
[HttpGet]
public IActionResult TestNotFound()
{
    return NotFound();
}

Swagger效果:


可以看到HTTP 状态代码 404。 很标准、很典型。

7.Unauthorized()

代码:

csharp 复制代码
/// <summary>
/// 测试Unauthorized()
/// </summary>
/// <returns></returns>
[HttpGet]
public IActionResult TestUnauthorized()
{
    return Unauthorized();
}

Swagger效果:


可以看到HTTP 状态代码 401。

8.ValidationProblem()

代码:

csharp 复制代码
/// <summary>
/// 测试ValidationProblem()
/// </summary>
/// <returns></returns>
[HttpGet]
public IActionResult TestValidationProblem()
{
    return ValidationProblem();
}

Swagger效果:


可以看到HTTP 状态代码 400。

9.PhysicalFile()

代码:

csharp 复制代码
/// <summary>
/// 测试PhysicalFile()
/// </summary>
/// <returns></returns>
[HttpGet]
public IActionResult TestPhysicalFile()
{
    var str = Environment.CurrentDirectory;
    Debug.WriteLine(str);
    var filePath = Path.Combine("E:\\csharpcode2022\\ConsoleApp1\\WebApplication1\\bin\\Debug", "1.txt");
    return PhysicalFile(filePath, "application/text", "1.txt");
}

Swagger效果:

可以看到HTTP 状态代码 200。

10.总结

  1. 本人认为WEB服务器本身的状态码与业务的代码应该不是同一个概念,不应该混用。代码只要执行到Controller里面,如果有问题,那就一定是业务有问题,与服务器本身没有关系。
  2. 基于第1点的认识,以上列举的9个函数中,貌似只有Content()、Ok()、Unauthorized()与PhysicalFile()能直接用在业务代码中。而Unauthorized()能用,是把用户的权限提升到WEB服务器的权限。

在微软文档StatusCodes类中可以查看更全面的状态代码:https://learn.microsoft.com/zh-cn/dotnet/api/microsoft.aspnetcore.http.statuscodes?view=aspnetcore-8.0

二、Swagger配置

1.Program.cs中代码修改

builder.Services.AddSwaggerGen();

改成如下代码:

csharp 复制代码
builder.Services.AddSwaggerGen(options =>
{
    options.SwaggerDoc("v1", new OpenApiInfo
    {
        Version = "v1",
        Title = "测试MVC文档",
        Description = "An ASP.NET Core Web API"
    });

    // using System.Reflection;
    var xmlFilename = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
    options.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, xmlFilename));
});

2.Visual Studio 2022设置

项目右击,选择"属性",然后"生成"=>"输出",勾选文档文件

Swagger接口效果:

到这里可以知道Swagger界面里的一些内容是根据一个xml文档来的。

三、dotnet8跨域处理

Program.cs中新增2处代码,亲测有效。

csharp 复制代码
//添加跨域策略
builder.Services.AddCors(options =>
{
    options.AddPolicy("CorsPolicy", opt => opt.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod());
});

//使用跨域策略
app.UseCors("CorsPolicy");

跨域测试代码:

html 复制代码
<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>测试</title>
		<script type="text/javascript" src="jquery.min.js"></script>
	</head>
	<body>
		<br>
		<br>
		<div>
			<button onclick="SendGet()">get</button>
		</div>
		<br>
		<br>
		<div>
			<button onclick="SendPost()">post</button>
		</div>
		<br>
		<br>
	</body>
	<script type="text/javascript">		
		function SendGet(){
			 $.get("http://localhost:5262/Test/TestContent?content=123",function(data,status){
			
			    alert("Data: " + data + "\nStatus: " + status);
			
			  });
		}
		
		function SendPost(){
			$.post("http://localhost:5262/Test/TestOk?param=%7B%22name%22%3A%20%22Tom%22%7D",
			  {
			    name:"Tom",
			    age:3
			  },
			
			  function(data,status){
			
			    alert("Data: " + data + "\nStatus: " + status);
			
			  });
		}
	</script>
</html>
相关推荐
IDOlaoluo3 小时前
VS2017 安装 .NET Core 2.2 SDK 教程(包括 dotnet-sdk-2.2.108-win-x64.exe 安装步骤)
.netcore
靓仔建3 小时前
Asp.net core用Swashbuckle.AspNetCore库出现错误信息:No operations defined in spec!
后端·asp.net·swagger
渣哥3 小时前
不加 @Primary?Spring 自动装配时可能直接报错!
javascript·后端·面试
汤姆yu3 小时前
2025版基于springboot的美食食品商城系统
spring boot·后端·美食
CodeLiving4 小时前
使用Funasr部署语音识别websockt案例
后端
天天摸鱼的java工程师4 小时前
Java 版 “国庆头像生成器”:8 年老开发的实用小工具
java·后端
用户4099322502124 小时前
PostgreSQL新手SQL总翻车?这7个性能陷阱你踩过没?
后端·ai编程·trae
自由的疯4 小时前
java调chrome浏览器显示网页
java·前端·后端