asp.net mvc web-api フィルター 実行順序と、ModelStateのエラー対応

参考

garafu.blogspot.jp

OnActionExecuting、OnActionExecuted

tech.sanwasystem.com

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http;
using System.Web.Http.Filters; //★こちらを参照
using Newtonsoft.Json;
using MvcHunter.Domain.Common.Data;
using System.Web.Http.Controllers;
   :
public class ApiValidationAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(HttpActionContext actionContext)
    {
        Debug.WriteLine("★OnActionExecuting:" + actionContext.Request.RequestUri.ToString());

       // パラメータを確認
       var log = new
       {
            LogType = "OnActionExecuting",
            Controller = actionContext.ControllerContext.Controller.ToString(),
            Method = actionContext.Request.Method.Method,
            RequestUri = actionContext.Request.RequestUri,
            RequestHeaders = actionContext.Request.Headers,
       };
       Debug.WriteLine(JsonConvert.SerializeObject(log));

        // パラメータエラー
        if (!actionContext.ModelState.IsValid)
        {
            var errorMsgs = actionContext.ModelState.SelectMany(x => x.Value.Errors.Select(z => z.ErrorMessage));

            List<object> list = new List<object>();
            foreach (var item in errorMsgs)
            {
                list.Add(new { code = "100", msg=item});
            }

            object param = new { status = (int)HttpStatusCode.OK, errors = list };

            //var serializer = new JavaScriptSerializer();
            //var json = serializer.Serialize(param);
            var json = JsonConvert.SerializeObject(param);

            HttpResponseMessage responsemsg = new HttpResponseMessage();
            responsemsg.StatusCode = HttpStatusCode.OK;
            responsemsg.Content = new StringContent(json);
            actionContext.Response = responsemsg;

            //var param = new Hashtable();
            //param["code"] = "E100";
            //param["message"] = "parameter error!";
            //var serializer = new JavaScriptSerializer();
            //var json = serializer.Serialize(param);
            //HttpResponseMessage responsemsg = new HttpResponseMessage();
            //responsemsg.StatusCode = HttpStatusCode.BadRequest;
            //responsemsg.Content = new StringContent(json);
            //actionContext.Response = responsemsg;
        }

        base.OnActionExecuting(actionContext);
    }
    public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
    {
        Debug.WriteLine("★OnActionExecuted:" + actionExecutedContext.Request.RequestUri.ToString());

        var log = new
        {
            LogType = "OnActionExecuted",
            HTTPStatus = (actionExecutedContext.Response == null) ? "" : actionExecutedContext.Response.StatusCode.ToString(),
            Request = actionExecutedContext.Request.ToString(),
            Parameter = actionExecutedContext.ActionContext.ActionArguments,
            Response = (actionExecutedContext.Response == null || actionExecutedContext.Response.Content == null) ? "" : actionExecutedContext.Response.Content.ReadAsStringAsync().Result,
        };
        Debug.WriteLine(JsonConvert.SerializeObject(log));

        base.OnActionExecuted(actionExecutedContext);   
    }
}