简体   繁体   English

ASP.NET MVC - 用于控制器的JSON.NET扩展方法

[英]ASP.NET MVC - JSON.NET extension method for controller

I just added JSON.NET to my project, and I would like to create an extension method called JsonNet that behaves the same way as the Json method, but uses JSON.NET instead. 我刚刚将JSON.NET添加到我的项目中,我想创建一个名为JsonNet的扩展方法,其行为与Json方法相同,但使用的是JSON.NET。

I have a class here that extends JsonResult using JSON.NET: 我在这里有一个使用JSON.NET扩展JsonResult的类:

public class JsonNetResult : JsonResult {
    public override void ExecuteResult(ControllerContext context) {
        if (context == null)
            throw new ArgumentNullException("context");

        var response = context.HttpContext.Response;

        response.ContentType = !String.IsNullOrEmpty(ContentType)
            ? ContentType
            : "application/json";

        if (ContentEncoding != null)
            response.ContentEncoding = ContentEncoding;

        var serializedObject = JsonConvert.SerializeObject(Data, Formatting.Indented);
        response.Write(serializedObject);
    }
}

Underneath the ExecuteResult method, I tried to add these: 在ExecuteResult方法下面,我尝试添加以下内容:

public static JsonNetResult JsonNet(this Controller controller, object data) {
    var result = new JsonNetResult();
    result.Data = data;
    return result;
}

public static JsonNetResult JsonNet(this Controller controller, object data, JsonRequestBehavior behavior) {
    var result = new JsonNetResult();
    result.Data = data;
    result.JsonRequestBehavior = behavior;
    return result;
}

And then I have my controller: 然后我有我的控制器:

public class SomethingController : Controller {
    public ActionResult SomeAction() {
        object data = SomeClass.GetData();
        return JsonNet(data, JsonRequestBehavior.AllowGet);
    }
}

And the compiler cannot find the JsonNet method. 并且编译器找不到JsonNet方法。 Even when I try this: 即使我尝试这个:

return ((Controller)this).JsonNet(data, JsonRequestBehavior.AllowGet);

it still doesn't work. 它仍然无法正常工作。

If I copy the code in JsonNet into SomeAction, it works just fine, so I know SomethingController can see JsonNetResult. 如果我将JsonNet中的代码复制到SomeAction中,它可以正常工作,所以我知道SomethingController可以看到JsonNetResult。

If it helps, the two classes are in separate namespaces. 如果有帮助,这两个类位于不同的名称空间中。

This is the one I use now, it also has comments for the pages where I pulled some of the source from. 这是我现在使用的那个,它也对我从中提取一些来源的页面有评论。 I've made tweaks of my own though, including the extension methods. 我已经对自己进行了调整,包括扩展方法。

And as mentioned, you need to have the appropriate using namespace added to your controller. 如上所述,您需要在控制器中添加适当的using命名空间。

I just call it using return this.JsonNet(data) . 我只是使用return this.JsonNet(data)来调用它。 The overrides I just have for allowing customization of the Formatting, and one because I ran into JS plugin that required the content type to be 'plain/text'. 我只是允许自定义格式化的覆盖,还有一个因为我遇到了需要内容类型为“普通/文本”的JS插件。

//http://james.newtonking.com/archive/2008/10/16/asp-net-mvc-and-json-net.aspx
public class JsonNetResult : ActionResult
{
    public Encoding ContentEncoding { get; set; }
    public string ContentType { get; set; }
    public object Data { get; set; }

    public JsonSerializerSettings SerializerSettings { get; set; }
    public Formatting Formatting { get; set; }

    public JsonNetResult()
    {
        SerializerSettings = new JsonSerializerSettings
            {
                //http://odetocode.com/blogs/scott/archive/2013/03/25/asp-net-webapi-tip-3-camelcasing-json.aspx
                #if DEBUG
                Formatting = Formatting.Indented, //Makes the outputted Json for structures for easier reading by a human, only needed in debug
                #endif
                ContractResolver = new CamelCasePropertyNamesContractResolver() //Makes the default for properties outputted by Json to use camelCaps
            };
    }

    public override void ExecuteResult(ControllerContext context)
    {
        if (context == null)
            throw new ArgumentNullException("context");

        HttpResponseBase response = context.HttpContext.Response;

        response.ContentType = !string.IsNullOrEmpty(ContentType)
                                   ? ContentType
                                   : "application/json";

        if (ContentEncoding != null)
            response.ContentEncoding = ContentEncoding;

        if (Data != null)
        {
            JsonTextWriter writer = new JsonTextWriter(response.Output) {Formatting = Formatting};

            JsonSerializer serializer = JsonSerializer.Create(SerializerSettings);
            serializer.Serialize(writer, Data);

            writer.Flush();
        }
    }
}

public static class JsonNetExtenionMethods
{
    public static ActionResult JsonNet(this Controller controller, object data)
    {
        return new JsonNetResult() {Data = data};
    }

    public static ActionResult JsonNet(this Controller controller, object data, string contentType)
    {
        return new JsonNetResult() { Data = data, ContentType = contentType };
    }

    public static ActionResult JsonNet(this Controller controller, object data, Formatting formatting)
    {
        return new JsonNetResult() {Data = data, Formatting = formatting};
    }
}

Extension methods will not be found by the compiler unless they are in a static class. 除非它们在静态类中,否则编译器将找不到扩展方法。 Try putting your JsonNet methods in their own static class called eg JsonNetExtensions . 尝试将JsonNet方法放在他们自己的静态类中,例如JsonNetExtensions Also make sure that your extensions class is either in the same namespace as your controllers, or your controllers have a using statement at the top with the namespace of the extensions class. 还要确保扩展类与控制器位于同一名称空间中,或者控制器在顶部使用扩展类名称空间的using语句。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM