c# - 在 ASP.NET MVC 4 ActionFilterAttribute 中引发异常的正确方法

标签 c# asp.net-mvc-3

请注意,这是针对 MVC 4 中的 ApiController 的,尽管我认为它不应该改变任何东西。

 public class OAuthFilter : System.Web.Http.ActionFilterAttribute
 {
       public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext)
       {
              if (checkVerified())
              {
                   // How to raise a 401 or some other type of exception.
              }
       }        
 }

最佳答案

您可以设置 HttpActionContext 的结果属性:

public override void OnActionExecuting(HttpActionContext actionContext)
{
    if (checkVerified())
    {
        actionContext.Response = 
            new HttpResponseMessage(HttpStatusCode.Unauthorized);
    }
}

你可能只是扔:

throw new HttpResponseException(HttpStatusCode.Unauthorized);

但我还没有检查过那个。

关于c# - 在 ASP.NET MVC 4 ActionFilterAttribute 中引发异常的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9916143/

相关文章:

javascript - JS/C# 接口(interface)的 API 标准 - Camel 与 Pascal 案例

c# - 以编程方式在 Entity Framework mvc 4 中创建表

css - 在 mvc 解决方案中存储较少源文件的约定?

ASP.NET MVC3 文件上传不工作

c# - MVC3 自定义 View 引擎

c# - 我们翻译网站的方式是否会导致性能问题?

c# - ArrayList 到 C# 中的 int[]

c# - 多个 FileSystemWatcher 是个好主意吗?

asp.net-mvc - 在Webgrid中将 bool 值显示为复选框

c# - 从 C# 中的电子表格中提取时出现错误 "Specified cast is not valid"