找不到ToJSON方法 - 需要哪个命名空间?

时间:2015-09-24 06:29:14

标签: asp.net-mvc asp.net-web-api nlog

我想将.net WEB API请求 - 响应记录到新创建的文件中。所以,我在我的项目中实现了NLog机制,效果很好。但仍然低于代码.ToJSON()行没有得到解决。我无法确定使用它需要哪个命名空间。有什么遗漏的吗?

我引用这两篇文章但仍然无法弄清楚。

1)http://www.codeproject.com/Articles/1028416/RESTful-Day-sharp-Request-logging-and-Exception-ha

2)http://www.strathweb.com/2012/06/using-nlog-to-provide-custom-tracing-for-your-asp-net-web-api/

.net名称空间

using NLog;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Web;
using System.Web.Http.Tracing;
using System.Net.Http;
using System.Text;
     if (level != TraceLevel.Off)
            {
                if (traceAction != null && traceAction.Target != null)
                {
                    category = category + Environment.NewLine + "Action     Parameters : " + traceAction.Target.ToJSON();  //this ToJSON doesn't get resolved. which namespace should I include? 
                }
                var record = new TraceRecord(request, category, level);
                if (traceAction != null) traceAction(record);
                Log(record);
            }

2 个答案:

答案 0 :(得分:2)

没有这样的方法。 codeproject.com中的示例向您展示了如何自己制作:

1: 1804.9
2: 770.0
3: 20.0

答案 1 :(得分:0)

更好的方法是使用JSON.Net。它很可能已在您的项目中引用,System.Web.Extensions.dll现在很古老(performance is terrible):

public void Trace(HttpRequestMessage request, string category, TraceLevel level, Action<TraceRecord> traceAction)
{
    if (level != TraceLevel.Off)
    {
        if (traceAction != null && traceAction.Target != null)
        {
            category = category + Environment.NewLine + "Action Parameters : " + JsonConvert.SerializeObject(traceAction.Target);
        }
        var record = new TraceRecord(request, category, level);
        if (traceAction != null) traceAction(record);
        Log(record);
    }
}