2013-11-26 33 views
5

我讀http://www.asp.net/web-api/overview/security/working-with-ssl-in-web-api並試圖從該頁面使用的代碼工作:HttpResponseMessage不是在網絡API(.NET 4.5)

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Net; 
using System.Net.Http; 
using System.Web; 
using System.Web.Http; 
using System.Web.Http.Filters; 
using System.Web.Http.Controllers; 

public class RequireHttpsAttribute : AuthorizationFilterAttribute 
{ 
    public override void OnAuthorization(HttpActionContext actionContext) 
    { 
     if (actionContext.Request.RequestUri.Scheme != Uri.UriSchemeHttps) 
     { 
      actionContext.Response = new HttpResponseMessage(System.Net.HttpStatusCode.Forbidden) 
      { 
       ReasonPhrase = "HTTPS Required" 
      }; 
     } 
     else 
     { 
      base.OnAuthorization(actionContext); 
     } 
    } 
} 

當我建我沒有得到一個錯誤,但運行時給出了這樣的錯誤:

CS0012: The type 'System.Net.Http.HttpRequestMessage' is defined in an assembly that is not referenced. You must add a reference to assembly 'System.Net.Http, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'.

我已經在我的項目的引用文件夾中引用了System.Net.Http。如果我看看它的屬性,它會顯示版本4.0.0.0和運行時版本4.0.30319。我的項目屬性說目標框架是.NET 4.5。

我在VS2013 Express中的智能感知也不想拿起任何與HttpResponseMessage或HttpRequestMessage有關的事情。

我試過刪除引用並重新添加它,但無濟於事。

任何幫助將非常感激。

回答

8

在你的web.config嘗試添加:

<configuration> 
    <system.web> 
     <compilation> 
      <assemblies> 
       <add assembly="System.Net.Http, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/> 
      </assemblies> 
      </compilation> 
    </system.web> 
</configuration> 
+1

不要忘記'system.web'和'assemblies'之間的'compilation'元素。 –

0

嘗試增加組件的配置文件

<runtime> 
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"> 
    <dependentAssembly> 
     <assemblyIdentity name="System.Net.Http" publicKeyToken="b03f5f7f11d50a3a" /> 
     <bindingRedirect oldVersion="0.0.0.0-4.0.0.0" newVersion="4.0.0.0" /> 
    </dependentAssembly> 
    </assemblyBinding> 
</runtime 
4

嗯結合,我可能會晚點,但以防萬一別人遇到這個問題。

首先,你需要找到一個字符串:

<compilation debug="true" targetFramework="4.5"/> 

,使其不能自行關閉標籤這樣的:

<compilation debug="true" targetFramework="4.5"> 
</compilation> 

接下來,添加組件標籤內彙編信息,您所以它看起來像這樣:

<compilation debug="true" targetFramework="4.5"> 
     <assemblies> 
     <add assembly="System.Net.Http, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/> 
     </assemblies> 
</compilation> 

並重建您的解決方案。 看看this link

+0

這爲我做了詭計。它編譯沒有問題,但智能感知顯示它在剃鬚刀視圖引擎中的錯誤,直到我重新啓動Visual Studio。 –