//фильтр для валидации
public class ValidateModelAttribute: Attribute, IActionFilter
{
public bool AllowMultiple { get; } = false;
public Task<HttpResponseMessage> ExecuteActionFilterAsync(HttpActionContext actionContext,
CancellationToken cancellationToken, Func<Task<HttpResponseMessage>> continuation)
{
//примерно таким способом у меня все работает
if (!actionContext.ModelState.IsValid)
{
// получаем ошибки валидации по пути actionContext.ModelState[0..i].Error[0..j].ErrorMessage
var errors = (
from error in actionContext.ModelState
select new ErrorData("", error.Value.Errors[0].ErrorMessage) {Subject = error.Key}).ToArray();
throw new MyAwesomeValidationException("0x015", "Ошибка валидации") {ErrorData = errors};
}
return null;
}
}
//фильтр для ошибок
public class MyAwesomeExceptionFilterAttribute : ExceptionFilterAttribute
{
public override void OnException(HttpActionExecutedContext actionExecutedContext)
{
var result = new ApiResult<ErrorData[]>() { Result = false };
var sp= actionExecutedContext.Exception as MyAwesomeException;
if (sp!= null)
{
result.Error = sp.Message;
result.ErrorCode = sp.Code;
result.Data = sp.ErrorData;
}
else
{
result.Error = actionExecutedContext.Exception.Message;
result.ErrorCode = "";
}
actionExecutedContext.Response = new HttpResponseMessage(HttpStatusCode.OK);
actionExecutedContext.Response.Content = new ObjectContent<ApiResult<ErrorData[]>>(result,new JsonMediaTypeFormatter());
}
}
var items = db.Mods.Where(m=>m.SomeField==model.SomeField);
var itemId = db.Mods.FirstOrDefault(m=>m.SomeField==model.SomeField).Select(m=>m.Id);
var itemId = db.Mods.Single(m=>m.SomeField==model.SomeField).Select(m=>m.Id);
<customErrors mode="RemoteOnly" defaultRedirect="~/errors/error.aspx">
<error statusCode="500" redirect="~/errors/error500.aspx" redirectMode="ResponseRewrite" />/>
</customErrors>
<asp:Label runat="server" ID="ErrorMessage"></asp:Label>
protected void Page_Load(object sender, EventArgs e)
{
var error = HttpContext.Current.Server.GetLastError();
this.ErrorMessage = error.Message;
}