1

我正在构建一个 .NET 4.5 MVC 4 Web API,它将公开公开我希望安全访问的控制器方法。我创建了一个动作过滤器属性来检查正确编码的 RSA 令牌,为简洁起见,如下所示:

    public class TokenValidationAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(HttpActionContext actionContext)
    {
        try
        {
            //authorize user
        }
        catch (Exception)
        {                
            actionContext.Response = new HttpResponseMessage(HttpStatusCode.Forbidden)
            {
                Content = new StringContent("Unauthorized User")
            };                
        }
    }
}

然后在我的 .NET 3.5 CF 应用程序中,我将执行以下操作:

public static List<string> GetAvailableProjectIds()
        {
        var idList = new List<string>();
        var url = "the url";
        var req = CreateRequest(url, true);

        try
        {
            using (var response = (HttpWebResponse)req.GetResponse())
            {
                //do something with the resonse
            }
        }
        catch (Exception ex)
        {

        }

        return idList;
    }

捕获的异常是 WebException 并包含正确的 403 禁止状态代码。但没有什么比我能找到的更有帮助的了。

有没有办法获取 Content 属性,以便我可以向最终用户显示他们尝试使用“未经授权的用户”进行身份验证?

4

1 回答 1

0

我从来没有真正喜欢过这种行为,它在通信正常时使用异常。尝试添加此扩展方法:

private static HttpResponse GetAnyResponse(this HttpRequest req)
{
   HttpResponse retVal = null;

   try
   {
      retVal = (HttpWebResponse)req.GetResponse()
   }
   catch (WebException webEx)
   {
      retVal = webEx.Response;
   }
   catch (Exception ex)
   {
      // these are the "bad" exceptions, let them pass
      throw;
   }

   return webEx;   
}

然后将您的代码更改为:

using (var response = (HttpWebResponse)req.GetAnyResponse())
{
    //do something with the resonse
}
于 2013-02-27T13:38:11.140 回答