0

这是我的自定义属性

 public class CaptureMetrics : ActionFilterAttribute
 {
    private readonly string _metricType;
    public CaptureMetrics(MetricTypes metricType)
    {
        _metricType = metricType.ToString();
    }
    public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
    {
        try
        {
            string strJson;
            var reqPayload = context.HttpContext.Request.Body;
            using (var sr = new StreamReader(reqPayload))
            {
                strJson = await sr.ReadToEndAsync();
            }
            //Type t = Type.GetType(_metricType);
            //below I need to typecast the object to the equivalent DTO 
            var obj = JsonConvert.DeserializeObject(strJson); //line #
            // ToDo
        }
        catch (Exception)
        {
            //ToDo -> Log Exception
            throw;
        }
        finally
        {
            await next();
        }
    }
}

public enum MetricTypes
{
    ApiMetric
}

//DTO
public class ApiMetric
{
  //some properties
}

从控制器的动作来看,上述属性的使用如下

[CaptureMetrics(MetricTypes.ApiMetric)]
public async Task<IActionResult> Get([FromBody]ApiPayload payload)
{
}

在第 # 行,我需要将请求有效负载类型转换为等效的 DTO 类。

对于枚举(MetricType)中的每个条目,我都有一个同名的类(例如 ApiMetric)

如何在这里对对象进行类型转换?

4

0 回答 0