Я просто добавил JSON.NET в свой проект, и я хотел бы создать метод расширения JsonNet, который ведет себя так же, как метод Json, но вместо этого использует JSON.NET.
У меня есть класс, который расширяет JsonResult с помощью JSON.NET:
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);
}
}
Под методом 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;
}
И тогда у меня есть контроллер:
public class SomethingController : Controller {
public ActionResult SomeAction() {
object data = SomeClass.GetData();
return JsonNet(data, JsonRequestBehavior.AllowGet);
}
}
И компилятор не может найти метод JsonNet. Даже когда я пробую это:
return ((Controller)this).JsonNet(data, JsonRequestBehavior.AllowGet);
он все еще не работает.
Если я скопирую код в JsonNet в SomeAction, он работает нормально, поэтому я знаю, что SomethingController может видеть JsonNetResult.
Если это помогает, два класса находятся в разных пространствах имен.
Компилятор не найдет методы расширения, если они не находятся в статическом классе. Попробуйте JsonNet
методы JsonNet
в своем статическом классе, например, JsonNetExtensions
. Также убедитесь, что ваш класс расширений находится либо в том же пространстве имен, что и ваши контроллеры, либо у ваших контроллеров есть оператор using
сверху с пространством имен класса extensions.
JsonNetResult
; Я предполагаю, что он просто еще не пытался построить проект с такой договоренностью. Visual Studio не помечает это как ошибку (то есть с красными волнистыми подчеркиваниями) до тех пор, пока вы на самом деле не попытаетесь построить проект.
Это тот, который я использую сейчас, он также имеет комментарии для страниц, на которых я вытащил часть источника. Я сделал собственные настройки, включая методы расширения.
И, как уже упоминалось, вам необходимо иметь соответствующее пространство имен, добавленное к вашему контроллеру.
Я просто назову это, используя return this.JsonNet(data)
. Переопределения, которые я только что разрешил для настройки форматирования, и один, потому что я столкнулся с JS-плагином, который требовал, чтобы тип контента был "plain/text".
//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};
}
}