DD.WellWorkover.Cloud/AsbCloudWebApi/Extentions.cs

65 lines
2.1 KiB
C#
Raw Normal View History

using AsbCloudApp.Data.User;
using AsbCloudWebApi.Converters;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Security.Claims;
namespace Microsoft.AspNetCore.Mvc
{
public static class Extentions
{
2021-07-21 15:22:58 +05:00
public static int? GetCompanyId(this ClaimsPrincipal user)
{
var claimIdCompany = user.FindFirst(nameof(UserDto.IdCompany));
2021-07-21 15:22:58 +05:00
if (claimIdCompany is null)
return null;
2021-07-21 15:22:58 +05:00
return int.TryParse(claimIdCompany.Value, out int uid)
? uid
: null;
}
public static int? GetUserId(this ClaimsPrincipal user)
{
var userId = user.FindFirst(nameof(UserDto.Id));
if (userId is null)
return null;
return int.TryParse(userId.Value, out int uid)
? uid
: null;
}
/// <summary>
/// <para>
/// Returns BadRequest with ValidationProblemDetails as body
/// </para>
/// <para>
/// Используйте этот метод только если валидацию нельзя сделать через
/// атрибуты валидации или IValidatableObject модели.
/// </para>
/// </summary>
/// <param name="controller"></param>
/// <param name="paramName"></param>
/// <param name="error"></param>
/// <returns></returns>
public static BadRequestObjectResult ValidationBadRequest(this ControllerBase controller, string paramName, string error)
{
var errors = new Dictionary<string, string[]> {
{ paramName, new[]{ error } }
};
var problem = new ValidationProblemDetails(errors);
return controller.BadRequest(problem);
}
public static MvcOptions UseDateOnlyTimeOnlyStringConverters(this MvcOptions options)
{
TypeDescriptor.AddAttributes(typeof(DateOnly), new TypeConverterAttribute(typeof(DateOnlyTypeConverter)));
return options;
}
}
}