【问题标题】:Restrict MVC action to a contentType将 MVC 操作限制为 contentType
【发布时间】:2015-02-20 07:38:41
【问题描述】:

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

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

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

【问题讨论】:

  • 没有内置属性,但您可以创建自己的属性,例如 AjaxOnlyAttribute 来限制对 ajax 请求的调用
  • 在这种情况下使用 Web API 可能会更好。

标签: asp.net-mvc content-type


【解决方案1】:

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

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.
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-08-24
    • 1970-01-01
    • 1970-01-01
    • 2012-02-26
    • 2020-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多