From 5790142f81f2a94ad073834b1534acbf9b02ea3c Mon Sep 17 00:00:00 2001 From: 杨宇千 Date: Fri, 25 Oct 2019 18:36:02 +0800 Subject: Add NeutralResourcesLanguage. Conform to best practices. --- .../Controllers/Testing/TestingI18nController.cs | 36 ++++++++++++++ Timeline/Controllers/TokenController.cs | 29 ++++++----- Timeline/Controllers/UserAvatarController.cs | 57 ++++++++++------------ Timeline/Controllers/UserController.cs | 27 +++++----- 4 files changed, 88 insertions(+), 61 deletions(-) create mode 100644 Timeline/Controllers/Testing/TestingI18nController.cs (limited to 'Timeline/Controllers') diff --git a/Timeline/Controllers/Testing/TestingI18nController.cs b/Timeline/Controllers/Testing/TestingI18nController.cs new file mode 100644 index 00000000..febb56a5 --- /dev/null +++ b/Timeline/Controllers/Testing/TestingI18nController.cs @@ -0,0 +1,36 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Mvc; +using Microsoft.Extensions.Localization; + +// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860 + +namespace Timeline.Controllers.Testing +{ + [Route("testing/i18n")] + [ApiController] + public class TestingI18nController : Controller + { + private readonly IStringLocalizer _stringLocalizer; + + public TestingI18nController(IStringLocalizer stringLocalizer) + { + _stringLocalizer = stringLocalizer; + } + + [HttpGet("direct")] + [System.Diagnostics.CodeAnalysis.SuppressMessage("Performance", "CA1822:Mark members as static")] + public ActionResult Direct() + { + return Resources.Controllers.Testing.TestingI18nController.TestString; + } + + [HttpGet("localizer")] + public ActionResult Localizer() + { + return _stringLocalizer["TestString"].Value; + } + } +} diff --git a/Timeline/Controllers/TokenController.cs b/Timeline/Controllers/TokenController.cs index 4e32d26f..01f4778f 100644 --- a/Timeline/Controllers/TokenController.cs +++ b/Timeline/Controllers/TokenController.cs @@ -3,12 +3,11 @@ using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using Microsoft.IdentityModel.Tokens; using System; +using System.Globalization; using System.Threading.Tasks; +using Timeline.Helpers; using Timeline.Models.Http; using Timeline.Services; -using Timeline.Helpers; -using Microsoft.Extensions.Localization; -using System.Globalization; using static Timeline.Resources.Controllers.TokenController; namespace Timeline @@ -45,14 +44,12 @@ namespace Timeline.Controllers private readonly IUserService _userService; private readonly ILogger _logger; private readonly IClock _clock; - private readonly IStringLocalizer _localizer; - public TokenController(IUserService userService, ILogger logger, IClock clock, IStringLocalizer localizer) + public TokenController(IUserService userService, ILogger logger, IClock clock) { _userService = userService; _logger = logger; _clock = clock; - _localizer = localizer; } [HttpPost("create")] @@ -79,7 +76,7 @@ namespace Timeline.Controllers _logger.LogInformation(Log.Format(LogCreateSuccess, ("Username", request.Username), - ("Expire At", expireTime?.ToString(CultureInfo.CurrentUICulture.DateTimeFormat) ?? "default") + ("Expire At", expireTime?.ToString(CultureInfo.CurrentCulture.DateTimeFormat) ?? "default") )); return Ok(new CreateTokenResponse { @@ -90,14 +87,16 @@ namespace Timeline.Controllers catch (UserNotExistException e) { LogFailure(LogUserNotExist, e); - return BadRequest(new CommonResponse(ErrorCodes.Http.Token.Create.BadCredential, - _localizer["ErrorBadCredential"])); + return BadRequest(new CommonResponse( + ErrorCodes.Http.Token.Create.BadCredential, + ErrorBadCredential)); } catch (BadPasswordException e) { LogFailure(LogBadPassword, e); - return BadRequest(new CommonResponse(ErrorCodes.Http.Token.Create.BadCredential, - _localizer["ErrorBadCredential"])); + return BadRequest(new CommonResponse( + ErrorCodes.Http.Token.Create.BadCredential, + ErrorBadCredential)); } } @@ -132,7 +131,7 @@ namespace Timeline.Controllers LogFailure(LogVerifyExpire, e, ("Expires", innerException?.Expires), ("Current Time", _clock.GetCurrentTime())); return BadRequest(new CommonResponse( - ErrorCodes.Http.Token.Verify.Expired, _localizer["ErrorVerifyExpire"])); + ErrorCodes.Http.Token.Verify.Expired, ErrorVerifyExpire)); } else if (e.ErrorCode == JwtVerifyException.ErrorCodes.OldVersion) { @@ -140,20 +139,20 @@ namespace Timeline.Controllers LogFailure(LogVerifyOldVersion, e, ("Token Version", innerException?.TokenVersion), ("Required Version", innerException?.RequiredVersion)); return BadRequest(new CommonResponse( - ErrorCodes.Http.Token.Verify.OldVersion, _localizer["ErrorVerifyOldVersion"])); + ErrorCodes.Http.Token.Verify.OldVersion, ErrorVerifyOldVersion)); } else { LogFailure(LogVerifyBadFormat, e); return BadRequest(new CommonResponse( - ErrorCodes.Http.Token.Verify.BadFormat, _localizer["ErrorVerifyBadFormat"])); + ErrorCodes.Http.Token.Verify.BadFormat, ErrorVerifyBadFormat)); } } catch (UserNotExistException e) { LogFailure(LogVerifyUserNotExist, e); return BadRequest(new CommonResponse( - ErrorCodes.Http.Token.Verify.UserNotExist, _localizer["ErrorVerifyUserNotExist"])); + ErrorCodes.Http.Token.Verify.UserNotExist, ErrorVerifyUserNotExist)); } } } diff --git a/Timeline/Controllers/UserAvatarController.cs b/Timeline/Controllers/UserAvatarController.cs index 838a3928..7c77897d 100644 --- a/Timeline/Controllers/UserAvatarController.cs +++ b/Timeline/Controllers/UserAvatarController.cs @@ -1,7 +1,6 @@ using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; -using Microsoft.Extensions.Localization; using Microsoft.Extensions.Logging; using Microsoft.Net.Http.Headers; using System; @@ -13,6 +12,7 @@ using Timeline.Helpers; using Timeline.Models.Http; using Timeline.Models.Validation; using Timeline.Services; +using static Timeline.Resources.Controllers.UserAvatarController; namespace Timeline { @@ -56,15 +56,10 @@ namespace Timeline.Controllers private readonly IUserAvatarService _service; - private readonly IStringLocalizerFactory _localizerFactory; - private readonly IStringLocalizer _localizer; - - public UserAvatarController(ILogger logger, IUserAvatarService service, IStringLocalizerFactory localizerFactory) + public UserAvatarController(ILogger logger, IUserAvatarService service) { _logger = logger; _service = service; - _localizerFactory = localizerFactory; - _localizer = new StringLocalizer(localizerFactory); } [HttpGet("users/{username}/avatar")] @@ -82,15 +77,15 @@ namespace Timeline.Controllers { if (!EntityTagHeaderValue.TryParseStrictList(value, out var eTagList)) { - _logger.LogInformation(Log.Format(Resources.Controllers.UserAvatarController.LogGetBadIfNoneMatch, + _logger.LogInformation(Log.Format(LogGetBadIfNoneMatch, ("Username", username), ("If-None-Match", value))); - return BadRequest(HeaderErrorResponse.BadIfNonMatch(_localizerFactory)); + return BadRequest(HeaderErrorResponse.BadIfNonMatch()); } if (eTagList.FirstOrDefault(e => e.Equals(eTag)) != null) { Response.Headers.Add("ETag", eTagValue); - _logger.LogInformation(Log.Format(Resources.Controllers.UserAvatarController.LogGetReturnNotModify, ("Username", username))); + _logger.LogInformation(Log.Format(LogGetReturnNotModify, ("Username", username))); return StatusCode(StatusCodes.Status304NotModified); } } @@ -98,13 +93,13 @@ namespace Timeline.Controllers var avatarInfo = await _service.GetAvatar(username); var avatar = avatarInfo.Avatar; - _logger.LogInformation(Log.Format(Resources.Controllers.UserAvatarController.LogGetReturnData, ("Username", username))); + _logger.LogInformation(Log.Format(LogGetReturnData, ("Username", username))); return File(avatar.Data, avatar.Type, new DateTimeOffset(avatarInfo.LastModified), eTag); } catch (UserNotExistException e) { - _logger.LogInformation(e, Log.Format(Resources.Controllers.UserAvatarController.LogGetUserNotExist, ("Username", username))); - return NotFound(new CommonResponse(ErrorCodes.Http.UserAvatar.Get.UserNotExist, _localizer["ErrorGetUserNotExist"])); + _logger.LogInformation(e, Log.Format(LogGetUserNotExist, ("Username", username))); + return NotFound(new CommonResponse(ErrorCodes.Http.UserAvatar.Get.UserNotExist, ErrorGetUserNotExist)); } } @@ -116,14 +111,14 @@ namespace Timeline.Controllers { var contentLength = Request.ContentLength!.Value; if (contentLength > 1000 * 1000 * 10) - return BadRequest(ContentErrorResponse.TooBig(_localizerFactory, "10MB")); + return BadRequest(ContentErrorResponse.TooBig("10MB")); if (!User.IsAdministrator() && User.Identity.Name != username) { - _logger.LogInformation(Log.Format(Resources.Controllers.UserAvatarController.LogPutForbid, + _logger.LogInformation(Log.Format(LogPutForbid, ("Operator Username", User.Identity.Name), ("Username To Put Avatar", username))); return StatusCode(StatusCodes.Status403Forbidden, - new CommonResponse(ErrorCodes.Http.UserAvatar.Put.Forbid, _localizer["ErrorPutForbid"])); + new CommonResponse(ErrorCodes.Http.UserAvatar.Put.Forbid, ErrorPutForbid)); } try @@ -132,11 +127,11 @@ namespace Timeline.Controllers var bytesRead = await Request.Body.ReadAsync(data); if (bytesRead != contentLength) - return BadRequest(ContentErrorResponse.UnmatchedLength_Smaller(_localizerFactory)); + return BadRequest(ContentErrorResponse.UnmatchedLength_Smaller()); var extraByte = new byte[1]; if (await Request.Body.ReadAsync(extraByte) != 0) - return BadRequest(ContentErrorResponse.UnmatchedLength_Bigger(_localizerFactory)); + return BadRequest(ContentErrorResponse.UnmatchedLength_Bigger()); await _service.SetAvatar(username, new Avatar { @@ -144,30 +139,30 @@ namespace Timeline.Controllers Type = Request.ContentType }); - _logger.LogInformation(Log.Format(Resources.Controllers.UserAvatarController.LogPutSuccess, + _logger.LogInformation(Log.Format(LogPutSuccess, ("Username", username), ("Mime Type", Request.ContentType))); return Ok(); } catch (UserNotExistException e) { - _logger.LogInformation(e, Log.Format(Resources.Controllers.UserAvatarController.LogPutUserNotExist, ("Username", username))); - return BadRequest(new CommonResponse(ErrorCodes.Http.UserAvatar.Put.UserNotExist, _localizer["ErrorPutUserNotExist"])); + _logger.LogInformation(e, Log.Format(LogPutUserNotExist, ("Username", username))); + return BadRequest(new CommonResponse(ErrorCodes.Http.UserAvatar.Put.UserNotExist, ErrorPutUserNotExist)); } catch (AvatarFormatException e) { var (code, message) = e.Error switch { AvatarFormatException.ErrorReason.CantDecode => - (ErrorCodes.Http.UserAvatar.Put.BadFormat_CantDecode, _localizer["ErrorPutBadFormatCantDecode"]), + (ErrorCodes.Http.UserAvatar.Put.BadFormat_CantDecode, ErrorPutBadFormatCantDecode), AvatarFormatException.ErrorReason.UnmatchedFormat => - (ErrorCodes.Http.UserAvatar.Put.BadFormat_UnmatchedFormat, _localizer["ErrorPutBadFormatUnmatchedFormat"]), + (ErrorCodes.Http.UserAvatar.Put.BadFormat_UnmatchedFormat, ErrorPutBadFormatUnmatchedFormat), AvatarFormatException.ErrorReason.BadSize => - (ErrorCodes.Http.UserAvatar.Put.BadFormat_BadSize, _localizer["ErrorPutBadFormatBadSize"]), + (ErrorCodes.Http.UserAvatar.Put.BadFormat_BadSize, ErrorPutBadFormatBadSize), _ => - throw new Exception(Resources.Controllers.UserAvatarController.ExceptionUnknownAvatarFormatError) + throw new Exception(ExceptionUnknownAvatarFormatError) }; - _logger.LogInformation(e, Log.Format(Resources.Controllers.UserAvatarController.LogPutUserBadFormat, ("Username", username))); + _logger.LogInformation(e, Log.Format(LogPutUserBadFormat, ("Username", username))); return BadRequest(new CommonResponse(code, message)); } } @@ -178,23 +173,23 @@ namespace Timeline.Controllers { if (!User.IsAdministrator() && User.Identity.Name != username) { - _logger.LogInformation(Log.Format(Resources.Controllers.UserAvatarController.LogPutUserBadFormat, + _logger.LogInformation(Log.Format(LogPutUserBadFormat, ("Operator Username", User.Identity.Name), ("Username To Delete Avatar", username))); return StatusCode(StatusCodes.Status403Forbidden, - new CommonResponse(ErrorCodes.Http.UserAvatar.Delete.Forbid, _localizer["ErrorDeleteForbid"])); + new CommonResponse(ErrorCodes.Http.UserAvatar.Delete.Forbid, ErrorDeleteForbid)); } try { await _service.SetAvatar(username, null); - _logger.LogInformation(Log.Format(Resources.Controllers.UserAvatarController.LogDeleteSuccess, ("Username", username))); + _logger.LogInformation(Log.Format(LogDeleteSuccess, ("Username", username))); return Ok(); } catch (UserNotExistException e) { - _logger.LogInformation(e, Log.Format(Resources.Controllers.UserAvatarController.LogDeleteNotExist, ("Username", username))); - return BadRequest(new CommonResponse(ErrorCodes.Http.UserAvatar.Delete.UserNotExist, _localizer["ErrorDeleteUserNotExist"])); + _logger.LogInformation(e, Log.Format(LogDeleteNotExist, ("Username", username))); + return BadRequest(new CommonResponse(ErrorCodes.Http.UserAvatar.Delete.UserNotExist, ErrorDeleteUserNotExist)); } } } diff --git a/Timeline/Controllers/UserController.cs b/Timeline/Controllers/UserController.cs index 1771dc85..7b441c3a 100644 --- a/Timeline/Controllers/UserController.cs +++ b/Timeline/Controllers/UserController.cs @@ -1,7 +1,7 @@ using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; -using Microsoft.Extensions.Localization; using Microsoft.Extensions.Logging; +using System.Globalization; using System.Threading.Tasks; using Timeline.Authentication; using Timeline.Helpers; @@ -56,15 +56,11 @@ namespace Timeline.Controllers private readonly ILogger _logger; private readonly IUserService _userService; - private readonly IStringLocalizerFactory _localizerFactory; - private readonly IStringLocalizer _localizer; - public UserController(ILogger logger, IUserService userService, IStringLocalizerFactory localizerFactory) + public UserController(ILogger logger, IUserService userService) { _logger = logger; _userService = userService; - _localizerFactory = localizerFactory; - _localizer = localizerFactory.Create(GetType()); } [HttpGet("users"), AdminAuthorize] @@ -80,7 +76,7 @@ namespace Timeline.Controllers if (user == null) { _logger.LogInformation(Log.Format(LogGetUserNotExist, ("Username", username))); - return NotFound(new CommonResponse(ErrorCodes.Http.User.Get.NotExist, _localizer["ErrorGetUserNotExist"])); + return NotFound(new CommonResponse(ErrorCodes.Http.User.Get.NotExist, ErrorGetUserNotExist)); } return Ok(user); } @@ -93,10 +89,10 @@ namespace Timeline.Controllers { case PutResult.Create: _logger.LogInformation(Log.Format(LogPutCreate, ("Username", username))); - return CreatedAtAction("Get", new { username }, CommonPutResponse.Create(_localizerFactory)); + return CreatedAtAction("Get", new { username }, CommonPutResponse.Create()); case PutResult.Modify: _logger.LogInformation(Log.Format(LogPutModify, ("Username", username))); - return Ok(CommonPutResponse.Modify(_localizerFactory)); + return Ok(CommonPutResponse.Modify()); default: throw new InvalidBranchException(); } @@ -113,7 +109,7 @@ namespace Timeline.Controllers catch (UserNotExistException e) { _logger.LogInformation(e, Log.Format(LogPatchUserNotExist, ("Username", username))); - return NotFound(new CommonResponse(ErrorCodes.Http.User.Patch.NotExist, _localizer["ErrorPatchUserNotExist"])); + return NotFound(new CommonResponse(ErrorCodes.Http.User.Patch.NotExist, ErrorPatchUserNotExist)); } } @@ -124,12 +120,12 @@ namespace Timeline.Controllers { await _userService.DeleteUser(username); _logger.LogInformation(Log.Format(LogDeleteDelete, ("Username", username))); - return Ok(CommonDeleteResponse.Delete(_localizerFactory)); + return Ok(CommonDeleteResponse.Delete()); } catch (UserNotExistException e) { _logger.LogInformation(e, Log.Format(LogDeleteNotExist, ("Username", username))); - return Ok(CommonDeleteResponse.NotExist(_localizerFactory)); + return Ok(CommonDeleteResponse.NotExist()); } } @@ -147,13 +143,14 @@ namespace Timeline.Controllers { _logger.LogInformation(e, Log.Format(LogChangeUsernameNotExist, ("Old Username", request.OldUsername), ("New Username", request.NewUsername))); - return BadRequest(new CommonResponse(ErrorCodes.Http.User.Op.ChangeUsername.NotExist, _localizer["ErrorChangeUsernameNotExist", request.OldUsername])); + return BadRequest(new CommonResponse(ErrorCodes.Http.User.Op.ChangeUsername.NotExist, + string.Format(CultureInfo.CurrentCulture, ErrorChangeUsernameNotExist, request.OldUsername))); } catch (UsernameConfictException e) { _logger.LogInformation(e, Log.Format(LogChangeUsernameAlreadyExist, ("Old Username", request.OldUsername), ("New Username", request.NewUsername))); - return BadRequest(new CommonResponse(ErrorCodes.Http.User.Op.ChangeUsername.AlreadyExist, _localizer["ErrorChangeUsernameAlreadyExist"])); + return BadRequest(new CommonResponse(ErrorCodes.Http.User.Op.ChangeUsername.AlreadyExist, ErrorChangeUsernameAlreadyExist)); } // there is no need to catch bad format exception because it is already checked in model validation. } @@ -172,7 +169,7 @@ namespace Timeline.Controllers _logger.LogInformation(e, Log.Format(LogChangePasswordBadPassword, ("Username", User.Identity.Name), ("Old Password", request.OldPassword))); return BadRequest(new CommonResponse(ErrorCodes.Http.User.Op.ChangePassword.BadOldPassword, - _localizer["ErrorChangePasswordBadPassword"])); + ErrorChangePasswordBadPassword)); } // User can't be non-existent or the token is bad. } -- cgit v1.2.3