2015-03-03 71 views
1

我一直在將一些常見屬性移動到單獨的vs項目中,以便我可以在多個項目中輕鬆使用它們。一個屬性是的WebAPI控制器和確保請求是使用HTTPS:外部程序集中的屬性

public class EnsureHttpsAttribute : ActionFilterAttribute 
{ 
    public override void OnActionExecuting(HttpActionContext actionContext) 
    { 
     if(actionContext == null) 
     { 
      throw new ArgumentNullException("actionContext"); 
     } 

     if(actionContext.Request.RequestUri.Scheme != Uri.UriSchemeHttps) 
     { 
      HandleNonHttpsRequest(actionContext); 
     } 
    } 

    protected virtual HttpResponseMessage HandleNonHttpsRequest(HttpActionContext actionContext) 
    { 
     HttpResponseMessage response = null; 

     if(actionContext.Request.Method.Equals(HttpMethod.Get) || actionContext.Request.Method.Equals(HttpMethod.Head)) 
     { 
      UriBuilder newUrlBuilder = new UriBuilder(actionContext.Request.RequestUri); 
      newUrlBuilder.Scheme = Uri.UriSchemeHttps; 
      newUrlBuilder.Port = 443; 

      response = actionContext.Request.CreateResponse(HttpStatusCode.Found); 

      response.Headers.Location = newUrlBuilder.Uri; 
     } 
     else 
     { 
      response = actionContext.Request.CreateResponse(HttpStatusCode.NotFound); 
     } 

     actionContext.Response = response; 

     return response; 
    } 

    public System.Threading.Tasks.Task<HttpResponseMessage> ExecuteAuthorizationFilterAsync(HttpActionContext actionContext, System.Threading.CancellationToken cancellationToken, Func<System.Threading.Tasks.Task<HttpResponseMessage>> continuation) 
    { 
     if(actionContext == null) 
     { 
      throw new ArgumentNullException("actionContext"); 
     } 

     if(actionContext.Request.RequestUri.Scheme != Uri.UriSchemeHttps) 
     { 
      return Task.FromResult<HttpResponseMessage>(HandleNonHttpsRequest(actionContext)); 
     } 
     else 
     { 
      return continuation(); 
     } 
    } 
} 

我然後添加屬性如下:

config.Filters.Add(new EnsureHttpsAttribute()); 

的問題是,當屬性是從一個單獨的參考項目,它不會被調用。該項目編譯和運行沒有問題 - 除了該屬性沒有得到執行。如果我將屬性移動到同一個webapi項目中,該屬性將被執行。我還有其他使用聲明來授權請求​​的屬性 - 這些屬性不會在單獨項目的一部分中執行。

有沒有人遇到過這個?

+0

對我來說就像一個魅力,你確定你在兩個項目中使用相同的System.Web.Http和System.Net.Http版本嗎? – 2015-03-03 14:40:33

+0

@JosVinke感謝您的回覆。我創建了一個新的web api項目,並嘗試使用單獨的項目 - 它按預期工作。我注意到,在這個新項目和原始版本中,System.Web.Http(4.0.0.0和5.2.3.0)的版本存在錯誤匹配 - 我更新了項目,以便它們都消耗5.2.3.0和一切都在工作。你知道爲什麼這可能導致了一個問題嗎?我會期待一個例外。 – markpirvine 2015-03-04 08:14:47

+0

好現在閱讀它的工作,但我不知道是什麼原因造成的問題。從4.0.0.0版本到5.2.3.0版本的ActionFilterAttribute實現(例如添加Async方法)之間有相當大的區別,但我不確定導致問題的原因可能是HTTP管道中的某些更改。如果你知道,請讓我知道。 – 2015-03-04 08:59:34

回答

0

應該可以將您的屬性放在一個外部項目中。

請確保您使用的是相同的System.Web.HttpSystem.Net.Http版本在兩個項目。