gpt4 book ai didi

c# - 是否有可能阻止 Action 成为 ContentResult?

转载 作者:太空狗 更新时间:2023-10-29 17:53:19 29 4
gpt4 key购买 nike

我正在尝试编写一个过滤器来包装数据以遵循 JSON API spec到目前为止,它适用于我直接返回 ActionResult 的所有情况,例如 ComplexTypeJSON。我试图让它在像 ComplexType 这样的情况下工作,在这种情况下我不必经常运行 Json 函数。

[JSONAPIFilter]
public IEnumerable<string> ComplexType()
{
return new List<string>() { "hello", "world" };
}

[JSONAPIFilter]
public JsonResult ComplexTypeJSON()
{
return Json(new List<string>() { "hello", "world" });
}

但是,当我导航到 ComplexType 时,当 public override void OnActionExecuted(ActionExecutedContext filterContext) 运行时,filterContext.Result 是一个内容结果,这只是一个字符串,其中 filterContext.Result.Content 很简单:

"System.Collections.Generic.List`1[System.String]"

有没有一种方法可以让 ComplexType 变成 JsonResult 而不是 ContentResult

对于上下文,这里是确切的文件:

测试 Controller .cs

namespace MyProject.Controllers
{
using System;
using System.Collections.Generic;
using System.Web.Mvc;

using MyProject.Filters;

public class TestController : Controller
{
[JSONAPIFilter]
public IEnumerable<string> ComplexType()
{
return new List<string>() { "hello", "world" };
}

[JSONAPIFilter]
public JsonResult ComplexTypeJSON()
{
return Json(new List<string>() { "hello", "world" });
}

// GET: Test
[JSONAPIFilter]
public ActionResult Index()
{
return Json(new { foo = "bar", bizz = "buzz" });
}

[JSONAPIFilter]
public string SimpleType()
{
return "foo";
}

[JSONAPIFilter]
public ActionResult Throw()
{
throw new InvalidOperationException("Some issue");
}
}
}

JSONPiFilter.cs

namespace MyProject.Filters
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;

using MyProject.Exceptions;
using MyProject.Models.JSONAPI;

public class JSONAPIFilterAttribute : ActionFilterAttribute, IExceptionFilter
{
private static readonly ISet<Type> IgnoredTypes = new HashSet<Type>()
{
typeof(FileResult),
typeof(JavaScriptResult),
typeof(HttpStatusCodeResult),
typeof(EmptyResult),
typeof(RedirectResult),
typeof(ViewResultBase),
typeof(RedirectToRouteResult)
};

private static readonly Type JsonErrorType = typeof(ErrorModel);

private static readonly Type JsonModelType = typeof(ResultModel);

public override void OnActionExecuted(ActionExecutedContext filterContext)
{
if (filterContext == null)
{
throw new ArgumentNullException("filterContext");
}

if (IgnoredTypes.Any(x => x.IsInstanceOfType(filterContext.Result)))
{
base.OnActionExecuted(filterContext);
return;
}

var resultModel = ComposeResultModel(filterContext.Result);
var newJsonResult = new JsonResult()
{
JsonRequestBehavior = JsonRequestBehavior.AllowGet,
Data = resultModel
};

filterContext.Result = newJsonResult;
base.OnActionExecuted(filterContext);
}

public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var modelState = filterContext.Controller.ViewData.ModelState;

if (modelState == null || modelState.IsValid)
{
base.OnActionExecuting(filterContext);
}
else
{
throw new ModelStateException("Errors in ModelState");
}
}

public virtual void OnException(ExceptionContext filterContext)
{
if (filterContext == null)
{
throw new ArgumentNullException("filterContext");
}

if (filterContext.Exception == null) return;

// Todo: if modelstate error, do not provide that message
// set status code to 404

var errors = new List<string>();

if (!(filterContext.Exception is ModelStateException))
{
errors.Add(filterContext.Exception.Message);
}

var modelState = filterContext.Controller.ViewData.ModelState;
var modelStateErrors = modelState.Values.SelectMany(x => x.Errors).Select(x => x.ErrorMessage).ToList();
if (modelStateErrors.Any()) errors.AddRange(modelStateErrors);

var errorCode = (int)System.Net.HttpStatusCode.InternalServerError;
var errorModel = new ErrorModel()
{
status = errorCode.ToString(),
detail = filterContext.Exception.StackTrace,
errors = errors,
id = Guid.NewGuid(),
title = filterContext.Exception.GetType().ToString()
};
filterContext.ExceptionHandled = true;
filterContext.HttpContext.Response.Clear();
filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
filterContext.HttpContext.Response.StatusCode = errorCode;

var newResult = new JsonResult() { Data = errorModel, JsonRequestBehavior = JsonRequestBehavior.AllowGet };

filterContext.Result = newResult;
}

private ResultModel ComposeResultModel(ActionResult actionResult)
{
var newModelData = new ResultModel() { };

var asContentResult = actionResult as ContentResult;
if (asContentResult != null)
{
newModelData.data = asContentResult.Content;
return newModelData;
}

var asJsonResult = actionResult as JsonResult;
if (asJsonResult == null) return newModelData;

var dataType = asJsonResult.Data.GetType();
if (dataType != JsonModelType)
{
newModelData.data = asJsonResult.Data;
}
else
{
newModelData = asJsonResult.Data as ResultModel;
}

return newModelData;
}
}
}

最佳答案

有两种选择:

1.使用ApiController代替Controller

apicontroller会返回json结果,默认序列化器是Newtonsoft.json (here) , 所以你可以像下面这样使用:

//the response type
public class SimpleRes
{
[JsonProperty(PropertyName = "result")]
public string Result;
}

//the controller
public class TestController : ApiController
{
[HttpGet]
[HttpPost]
[JSONAPIFilter]
public SimpleRes TestAction()
{
return new SimpleRes(){Result = "hello world!"};
}
}

2.如果您坚持使用Controller,请用您自己的ActionResult 包裹您的响应:

//json container
public class AjaxMessageContainer<T>
{
[JsonProperty(PropertyName = "result")]
public T Result { set; get; }
}

//your own actionresult
public class AjaxResult<T> : ActionResult
{
private readonly T _result;

public AjaxResult(T result)
{
_result = result;
}

public override void ExecuteResult(ControllerContext context)
{
context.HttpContext.Response.Clear();
context.HttpContext.Response.ContentType = "application/json";
var result = JsonConvert.SerializeObject(new AjaxMessageContainer<T>
{
Result = _result,
});
var bytes =
new UTF8Encoding().GetBytes(result);
context.HttpContext.Response.OutputStream.Write(bytes, 0, bytes.Length);
}
}

//your controller
[JSONAPIFilter]
public AjaxResult<List<String>> TestSimple()
{
return AjaxResult<List<String>>(new List<string>() { "hello", "world" });
}

如果你想从 filter 获取日志或其他东西的响应字符串:

var result  = filterContext.Response.Content.ReadAsStringAsync();

关于c# - 是否有可能阻止 Action 成为 ContentResult?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38127863/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com