c# - 如果用户未获得授权,则返回较少的数据
问题描述
我在控制器中有这个方法:
[Route("api/AppSearch/Search")]
[HttpPost]
[Authorize]
public async Task<ResponseEntity<AppSearchResponse>> Search([FromBody] AppSearchRequest request, string type = "")
{
IEnumerable<AppSearchResponse> data = await SearchServiceV2.Search(request.SearchCriteria, request.AppKeyColumn, request.Filters, request.MaxResults, type);
if (data == null)
{
var resp = new HttpResponseMessage(HttpStatusCode.NotFound)
{
Content = new StringContent(string.Format("Unknown type ", type)),
ReasonPhrase = "Unknown type"
};
throw new HttpResponseException(resp);
}
return this.AssembleSuccessResponse<AppSearchResponse>(data);
}
我想根据用户是否被授权返回不同的数据。如果用户被授权,我希望它返回 AppSearchResponse,如果没有,则返回一个包含 3 个 AppSearchResponse 成员的类。
我最初的想法是创建具有这 3 个字段的 AppSearchResponseBase,然后让 AppSearchResponse 扩展它。然后,检查用户是否在 Controller 方法中获得授权,并将data
变量序列化为 AppSearchResponseBase 或 AppSearchResponse
例如
if(authorized){
return this.AssembleSuccessResponse<AppSearchResponse>(data)
} else {
return this.AssembleSuccessResponse<AppSearchResponseBase>(data)
}
我最好只创建一个新资源api/AppSearch/SearchUnauthorized/
吗?
解决方案
我会做一些事情,比如有一个单一的类,AppSearchResponse
它的信息如下:
public AppSearchResponse{
public string Username {get;set;}
public DateTime Joined {get;set;}
// etc
public ExtendedData ExtendedData {get;set;}
}
ExtendedData
如果用户具有适当的访问权限,则仅填充(其中将包含“安全”字段)。在客户端,ExtendedData
如果null
客户端没有提供适当的凭据或其他什么。
推荐阅读
- reactjs - 如何从 Gatsby.js 中的 YAML 数组中获取图像
- java - 服务器 B 上的进程文件(位于服务器 A 上)
- java - 如何重试骆驼直达路线一次?
- java - 在 Adobe AEM 上集成 Google Sheets API
- c# - 使用 Autofac 将许多参数传递给所有组件的构造函数
- python - 使用 nan 的数据框操作:dtype 不起作用,矢量化问题
- sql-server - 将 Azure VM 迁移到另一个(SQL 版本升级)
- python - 从边界框获取对象[对象检测]
- python - 我如何引用本调查中的一个文本框以便能够自动输入它们?
- oracle-apex - Apex 中的主细节交互式网格