使用ASP.NET CORE 2中间件包装每个API响应中的通用组件

时间:2018-11-10 20:11:23

标签: c# asp.net-core-2.0

我有以下POCO课程:

public class CountryResult : APIResult
{
    public CountryResult()
    {
        Countries = new List<CountryDTO>();
    }

    public List<CountryDTO> Countries
    {
        get;
        set;
    }
}

public class APIResult
{
    public Locale Locale
    {
        get;
        set;
    }

    [JsonProperty("authorised")]
    public bool Authorized
    {
        get;
        set;
    }

    public string UserMessage
    {
        get;
        set;
    }

    = "";
}

json响应应始终保持一致。在每个有效负载响应中,被授权的localMessage用户消息都是常见的。

{
  "countries": [],
  "locale": {
    "localisationIdentifier": "en",
    "enabled": true,
    "language": "en",
    "country": "",
    "description": "English",
    "uuid": "37",
    "name": "English",
    "path": "/locales/en",
    "rightToLeft": false,
    "completeResponse": true,
    "scriptDirection": "ltr"
  },
  "authorised": false,
  "userMessage": ""
}

为了实现这一要求,我开发了CommonResponseMiddleware(Middlware组件)。

public class CommonResponseMiddleware
{
    private readonly RequestDelegate _next;
    private ICommonService _commonService;
    public CommonResponseMiddleware(RequestDelegate next, ICommonService commonService)
    {
        _next = next;
        _commonService = commonService;
    }

    public async Task Invoke(HttpContext context)
    {
        var currentBody = context.Response.Body;
        using (var memoryStream = new MemoryStream())
        {
            context.Response.Body = memoryStream;
            // Hit the web api and get the result
            await _next.Invoke(context);
            context.Response.Body = currentBody;
            memoryStream.Seek(0, SeekOrigin.Begin);
            var readToEnd = new StreamReader(memoryStream).ReadToEnd();
            var objResult = JsonConvert.DeserializeObject(readToEnd);
        }
    }
}

在objResult中,我获得了Entity:CountryResult的所有数据,但是APIResult(语言环境,authorized,userMessage)的所有属性仍设置为null。

如何设置APIResult的值并将其作为完整有效负载的一部分返回?

有人可以通过提供指导来帮助我解决此问题吗?

0 个答案:

没有答案