Compact Framework中的HttpResponseMessage内容属性

时间:2013-02-22 19:44:07

标签: c# asp.net-mvc asp.net-web-api compact-framework

我正在构建一个.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 Forbiden状态代码。但是我找不到任何帮助。

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

1 个答案:

答案 0 :(得分: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
}
相关问题