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>
相关推荐
a努力。1 小时前
【基础数据篇】数据等价裁判:Comparer模式
java·后端
开心猴爷1 小时前
苹果App Store应用程序上架方式全面指南
后端
小飞Coding1 小时前
三种方式打 Java 可执行 JAR 包,你用对了吗?
后端
bcbnb1 小时前
没有 Mac,如何在 Windows 上架 iOS 应用?一套可落地的工程方案
后端
用户8356290780511 小时前
从一维到二维:用Spire.XLS轻松将Python列表导出到Excel
后端·python
哈哈哈笑什么1 小时前
SpringBoot 企业级接口加密【通用、可配置、解耦的组件】「开闭原则+模板方法+拦截器/中间件模式」
java·后端·安全
期待のcode1 小时前
springboot依赖管理机制
java·spring boot·后端
我是小妖怪,潇洒又自在1 小时前
springcloud alibaba(八)链路追踪
后端·spring·spring cloud·sleuth·zipkin
疯狂的程序猴2 小时前
深入理解 iPhone 文件管理,从沙盒结构到开发调试的多工具协同实践
后端