将 MVC 操作限制为 contentType

Restrict MVC action to a contentType

MVC 中的任何属性是否限制了操作方法,以便该方法只处理接受 contentType: 'application/json' 请求?

[HttpPost]
public JsonResult GetLastestPosts(int categoryID, int lastPostID)
{
    var list = Posts.GetPostsByRootCategoryIDForAjax(categoryID, lastPostID);

    return new JsonResult()
    {
        Data = list
    };
}

没有任何开箱即用的功能可以根据 ContentType.But 限制请求,您可以随时编写自定义操作过滤器并在那里进行必要的限制。

public class RestrictionAttribute : FilterAttribute, IActionFilter
{
    public void OnActionExecuted(ActionExecutedContext filterContext)
    {

    }

    public void OnActionExecuting(ActionExecutingContext filterContext)
    {
        //Check for the content type take decision based on that.
    }
}