我需要通过从验证中发回错误代码来区分前端的错误。
目前,错误只会从
中发回string errorMessage
return new ValidationResult("Some error message")
。
我可以以某种方式发回错误代码,使用错误类型的枚举让我检查前端吗?
理论范例:
return new ValidationResult("Some default error message", MyErrorEnum.notEnoughCats)
答案 0 :(得分:1)
/// <summary>
///
/// </summary>
public class NotFoundException : Exception
{
/// <summary>
/// Сообщение об ошибке
/// </summary>
/// <param name="message"></param>
public NotFoundException(string message, int? codeAction=null) : base(message)
{
CodeAction = codeAction;
}
public int? CodeAction { get; set; }
}
拦截错误时:
public class ErrorsFilterAttribute : ExceptionFilterAttribute, IAutofacExceptionFilter
{
public override void OnException(HttpActionExecutedContext actionExecutedContext)
{
var errorMessage = new ErrorMessage(actionExecutedContext.Exception.Message, HttpStatusCode.InternalServerError);
if (actionExecutedContext.Exception is NotFoundException)
{
errorMessage.ErrorCode = (int)HttpStatusCode.NotFound;
isWarning = true;
errorMessage.CodeAction = ((NotFoundException) actionExecutedContext.Exception).CodeAction;
}
actionExecutedContext.Response = actionExecutedContext.Request.CreateResponse((HttpStatusCode)errorMessage.ErrorCode, errorMessage);
}
}
errorMessage它是我的返回类
/// <summary>
/// HTTP Code
/// </summary>
public int ErrorCode { get; set; }
/// <summary>
/// коде ошибки внутри сервиса
/// </summary>
public int? CodeAction { get; set; }
简单错误
{ "errorCode": 400, "codeAction": 2, "errors": {
"error": "bad values!" }}
答案 1 :(得分:1)
如果ajax + json
,我会用这种方法private string RenderRazorViewToString(string viewName, object model, Dictionary<string, object> oDicParametresViewData = null, string sHtmlFieldPrefix = "")
{
ViewData.Model = model;
if (oDicParametresViewData != null) foreach (var param in oDicParametresViewData) ViewData[param.Key] = param.Value;
if (sHtmlFieldPrefix != "") ViewData.TemplateInfo = new System.Web.Mvc.TemplateInfo { HtmlFieldPrefix = sHtmlFieldPrefix };
using (var sw = new StringWriter())
{
var viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
var viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
viewResult.View.Render(viewContext, sw);
viewResult.ViewEngine.ReleaseView(ControllerContext, viewResult.View);
return sw.GetStringBuilder().ToString();
}
}
Response.StatusCode = 666;
return Json(new
{
Html = RenderRazorViewToString("view", model),
});
谁打电话给你的验证结果? 你还可以返回局部视图吗?