Visual studio 2015 ASP.NET 5 MVC 6:通过接受标头路由到操作

Visual studio 2015 ASP.NET 5 MVC 6:通过接受标头路由到操作,visual-studio-2015,asp.net-core,asp.net-core-mvc,dnx,Visual Studio 2015,Asp.net Core,Asp.net Core Mvc,Dnx,假设有两种方法将数据发布到同一API端点,通过文件或通过请求体 是否可以通过同一资源的Accept标头路由到操作 请求主体: // Accept: application/json [HttpPost] public IActionResult PostText([FromBody]string text) { ... return new HttpOkResult(); } // Accept: application/x-www-form-urlencoded [HttpP

假设有两种方法将数据发布到同一API端点,通过文件或通过请求体

是否可以通过同一资源的Accept标头路由到操作

请求主体:

// 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();
}
按文件:

// 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();
}

您是否检查过:最好只实现
IActionConstraint
,而不是从
ActionMethodSelectorAttribute
@DanielJ.G派生。你能告诉我为什么使用IActionConstraint更好吗?因为
ActionMethodSelectorAttribute
已经是查看http方法的
IActionConstraint
的实现。您需要的是查看accept头的不同实现。那么,当您想要替换类提供的整个行为时,为什么要从类继承呢?但我在中没有看到任何与http方法相关的内容。根据描述,这是:“属性的基类,可以实现条件逻辑来启用或禁用给定请求的操作。”啊,我的错!我错误地假设该类是基于HTTP谓词过滤操作的类。