我希望创建一个Action Filter,用于检查用户是否创建了一些内容。如果他们不这样做,那么我想阻止执行该操作并返回错误。
这是我到目前为止所做的:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
using uQuiz.Domain.Abstract;
using uQuiz.WebUI.Helpers;
using Microsoft.AspNet.Identity;
using System.Net.Http;
using System.Net;
namespace uQuiz.WebUI.Controllers.Filters
{
/// <summary>
/// Determines whether the current logged in user has permission to edit the quiz requested
/// </summary>
public class CanEditQuiz : ActionFilterAttribute
{
IQuizEntities Context;
public CanEditQuiz()
{
}
public CanEditQuiz(IQuizEntities context)
{
this.Context = context;
}
public override void OnActionExecuting(HttpActionContext actionContext)
{
// Get the URL ID from the request
string urlId = actionContext.ModelState["urlId"].Value.ToString();
int userId = HttpContext.Current.User.Identity.GetUserId<int>();
if (!QuizHelper.IsQuizOwner(this.Context, urlId, userId))
{
// Prevent action executing
}
base.OnActionExecuting(actionContext);
}
}
}
我看到other questions提到将Result
设置为null
,但是当我覆盖OnActionExecuting
方法时,它已HttpActionContext
而不是ActionExecutingContext
出于某种原因?
如何阻止操作执行?
答案 0 :(得分:2)
您需要使用
System.Web.Mvc.ActionFilterAttribute
不
System.Web.Http.Filters.ActionFilterAttribute