gpt4 book ai didi

c# - Web API引发验证错误

转载 作者:行者123 更新时间:2023-12-03 07:58:58 25 4
gpt4 key购买 nike

我正在用C#编写Web api,试图遵循REST概念,即成功响应将为HttpStatus:200,验证错误将为433等。

我在global.asax中为整个应用程序注册了ExceptionFilter。

我的问题是,对于身份验证期间的验证错误,如果身份验证失败,则应如何将消息传递回客户端(它必须是不同的状态码,例如433或401)。

到目前为止,我正在从业务层引发自定义异常。是否建议在发生错误时引发异常?

以下是代码示例:

记录仪

public class ExceptionFilter : ExceptionFilterAttribute
{
public override void OnException(HttpActionExecutedContext context)
{
HttpResponseMessage response;
if (context.Exception is ExceptionBase)
{
response = context.Request.CreateResponse(HttpStatusCode.InternalServerError,
new ErrorDTO() { ErrorCode = (int)((ExceptionBase)context.Exception).ExceptionCode, Messages = ((ExceptionBase)context.Exception).Message });
}
else {
response = context.Request.CreateResponse(HttpStatusCode.InternalServerError,
new ErrorDTO() { ErrorCode = (int)HttpStatusCode.InternalServerError, Messages = "Error occured at server." });
}
context.Response = response;
base.OnException(context);
LogException(context);
}

private static void LogException(HttpActionExecutedContext context)
{
if (context.Exception != null)
{
Logger.Instance.LogError(context.ActionContext.ActionDescriptor.ActionName, context.Exception);
}
}

public override Task OnExceptionAsync(HttpActionExecutedContext context, CancellationToken cancellationToken)
{
return base.OnExceptionAsync(context, cancellationToken);
}
}

业务层
public AuthorizationTokenDTO AuthenticateUser(UserDTO userDTO)
{
User userEntity = _userRepository.GetUserWithAssociatedRole(userDTO.UserName);

if (userEntity == null)
throw new BLException("User does not exists.", ExceptionCode.RestApiValidation);

ActiveDirectory activeDirectory = _activeDirectoryRepository.GetEntityById(ConfigurationSettings.GetConfigSetting<int>(ApplicationConstants.ActiveDirectoryId));

if (activeDirectory == null)
throw new BLException("UserName or password is incorrect.", ExceptionCode.RestApiValidation);

using (var context = new PrincipalContext(ContextType.Domain))
{
string password = EncryptionUtility.Decrypt(userDTO.Password, ConfigurationSettings.GetConfigSetting<string>(ApplicationConstants.PrivateKeyForRSAEncryption));

if (!context.ValidateCredentials(userDTO.UserName, password))
throw new BLException("UserName or password is incorrect.", ExceptionCode.RestApiValidation);

UserAccessTokenDTO accessToken = GenrateNewUserAccessToken(userEntity);

if (accessToken == null)
throw new BLException("Error occured while generating access token.", ExceptionCode.RestApiValidation);

return GetAuthorizationTokenDTO(userEntity, accessToken);
}
}

是否建议在此类情况下引发异常?还是有更好的方式编写Web API?

最佳答案

可以说,ExceptionFilter应该只捕获“未处理的”异常。您可以将这些异常保留在BusinessLayer中并在 Controller 中捕获它们,或者返回某种对象。然后,只需从 Controller 返回带有相应HttpStatusCode的响应即可。

或者,您可以将响应包装成一些也了解HttpStatusCode(和错误消息)的信息。

关于c# - Web API引发验证错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38291133/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com