相关疑难解决方法(0)

将响应标头添加到ASP.NET核心中间件

我想像这样在我的ASP.NET Core WebApi中添加一个处理时中间件

public class ProcessingTimeMiddleware  
{
    private readonly RequestDelegate _next;

    public ProcessingTimeMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task Invoke(HttpContext context)
    {
        var watch = new Stopwatch();
        watch.Start();

        await _next(context);

        context.Response.Headers.Add("X-Processing-Time-Milliseconds", new[] { watch.ElapsedMilliseconds.ToString() });
    }
}
Run Code Online (Sandbox Code Playgroud)

但这样做会引发异常

 System.InvalidOperationException: Headers are readonly, reponse has already started.
Run Code Online (Sandbox Code Playgroud)

如何在响应中添加标头?

c# asp.net-core

34
推荐指数
4
解决办法
3万
查看次数

Json.net 向包含特定类型的每个类添加属性

我想为我的 json 为 DateTime 类型的每个属性添加一个属性。

我有一个自定义转换器并覆盖了 CreateProperties(见下文)。调试时返回的属性列表包含新值,但当 json 到达浏览器时,它不包含新属性

    protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
    {
        var properties = base.CreateProperties(type, memberSerialization);

        foreach(var prop in base.CreateProperties(type, memberSerialization))
        {
            if(prop != null
                && (prop.PropertyType == typeof(DateTime) || prop.PropertyType == typeof(DateTime?)))
            {
                properties.Add(new JsonProperty() {
                    PropertyName = String.Format("{0}$$type", prop.PropertyName),
                    PropertyType = typeof(String)
                });
            }
        }
        return properties;
    }
Run Code Online (Sandbox Code Playgroud)

想到的第一件事是新的 Json 属性在之后被擦除,因为它们是无效的。可能是因为它们没有价值,但是我看不到在这里设置价值的方法。

任何想法将是最受欢迎的

.net json.net

4
推荐指数
1
解决办法
926
查看次数

标签 统计

.net ×1

asp.net-core ×1

c# ×1

json.net ×1