如何在我想要的任何端点上执行操作?在 Asp.net Core WebAPI 中?

问题描述 投票:0回答:0

我正在创建一个 Asp.net Core WebAPI 项目。 我想在某些端点检查登录用户的用户名。

[HttpGet]
public IActionResult EndPoint1() // using HttpContext
{
  var userName = HttpContext.User.Identity.Name;
  // diong some action with userName
  
  // doing some action in endpoint1
}


[HttpGet]
public IActionResult EndPoint2() // using HttpContext
{
  var userName = HttpContext.User.Identity.Name; // Same Endpoint1
  // diong some action with userName // Same Endpoint1
  
  // doing some action in endpoint2
}


[HttpGet]
public IActionResult EndPoint3() // Without using HttpContext
{  
  // doing some action in endpoint3
}

在 Endpoint1 和 Endpoint2 中,我有相同的代码:

var userName = HttpContext.User.Identity.Name;
// diong some action with userName

我可以创建自定义属性(例如 [CheckUser])并在端点上使用它吗?

像这样:

[HttpGet]
[CheckUser] // optional attribute.
public IActionResult EndPoint1(){
  // doing some action in endpoint1
}

[HttpGet]
[CheckUser] // optional attribute.
public IActionResult EndPoint2(){
  // doing some action in endpoint2
}
asp.net attributes webapi core
© www.soinside.com 2019 - 2024. All rights reserved.