ASP.NET 5 MVC 6:通过 Accept 路由到操作 header

ASP.NET 5 MVC 6: Route to action by Accept header

假设有两种方法可以将数据 post 发送到同一个 API 端点,通过文件或通过请求 body。

是否可以通过 Accept header 为同一资源路由到操作?

根据要求body:

// Accept: application/json
[HttpPost]
public IActionResult PostText([FromBody]string text)
{
    ...
    return new HttpOkResult();
}

按文件:

// Accept: application/x-www-form-urlencoded
[HttpPost]
public IActionResult PostFile(IFormFile file)
{
    ...
    return new HttpOkResult();
}

为此使用操作约束。

动作约束

namespace WebApplication
{
    public class PostDataConstraint : ActionMethodSelectorAttribute
    {
        public override bool IsValidForRequest(RouteContext routeContext, ActionDescriptor action)
        {
            var httpContext = routeContext.HttpContext;
            var acceptHeader = //getting accept header from httpContext
            var currentActionName = action.DisplayName;

            if(actionName == "PostFile" and header == "application/x-www-form-urlencoded" ||
               actionName == "PostText" and header == "application/json")
            {
                return true
            }

            return false;
        }
    }
}

操作:

// Accept: application/json
[HttpPost]
[PostData]
public IActionResult PostText([FromBody]string text)
{
    ...
    return new HttpOkResult();
}

// Accept: application/x-www-form-urlencoded
[PostData]
[HttpPost]
public IActionResult PostFile(IFormFile file)
{
    ...
    return new HttpOkResult();
}