適用於 Visual Studio 2013 的 ASP.NET 和 Web 工具版本資訊ASP.NET and Web Tools for Visual Studio 2013 Release Notes

微軟by Microsoft

本文檔介紹了 2013 年可視化工作室的 ASP.NET 和網路工具的發布。This document describes the release of ASP.NET and Web Tools for Visual Studio 2013.

內容Contents

2013年可視化工作室ASP.NET和網路工具的新功能New Features in ASP.NET and Web Tools for Visual Studio 2013

安裝注意事項Installation Notes

ASP.NET和Web工具為可視化工作室2013捆綁在主安裝程式,可以在這裡下載。ASP.NET and Web Tools for Visual Studio 2013 are bundled in the main installer and can be downloaded here.

文件Documentation

有關 visual Studio 2013 的 ASP.NET 和 Web 工具的教程和其他資訊可從ASP.NET 網站獲得。Tutorials and other information about ASP.NET and Web Tools for Visual Studio 2013 are available from the ASP.NET web site.

軟體需求Software Requirements

ASP.NET和網路工具需要可視化工作室 2013。ASP.NET and Web Tools requires Visual Studio 2013.

2013年可視化工作室ASP.NET和網路工具的新功能New Features in ASP.NET and Web Tools for Visual Studio 2013

以下各節介紹版本中引入的功能。The following sections describe the features that have been introduced in the release.

一ASP.NETOne ASP.NET

隨著 Visual Studio 2013 的發表,我們朝著統一使用 ASP.NET 技術的經驗邁出了一步,以便您可以輕鬆混合和匹配所需的技術。With the release of Visual Studio 2013, we have taken a step towards unifying the experience of using ASP.NET technologies, so that you can easily mix and match the ones you want. 例如,可以使用 MVC 啟動專案,並在以後輕鬆地將 Web 窗體頁添加到專案,或在 Web 窗體專案中基架 Web API 中。For example, you can start a project using MVC and easily add Web Forms pages to the project later, or scaffold Web APIs in a Web Forms project. 一ASP.NET就是讓你作為開發人員更容易在ASP.NET中做你喜歡的事情。One ASP.NET is all about making it easier for you as a developer to do the things you love in ASP.NET. 無論您選擇何種技術,您都可以確信自己正在構建"一ASP.NET"的可信底層框架。No matter what technology you choose, you can have confidence that you are building on the trusted underlying framework of One ASP.NET.

新的 Web 專案體驗New Web Project Experience

我們在 Visual Studio 2013 中增強了創建新 Web 專案的經驗。We have enhanced the experience of creating new web projects in Visual Studio 2013. 「新建ASP.NET Web 專案」對話框中,您可以選擇所需的項目類型、配置任何技術組合(Web 窗體、MVC、Web API)、設定身份驗證選項以及添加單元測試專案。In the New ASP.NET Web Project dialog you can select the project type you want, configure any combination of technologies (Web Forms, MVC, Web API), configure authentication options, and add a unit test project.

新ASP.NET專案

新的對話框使您能夠更改許多範本的預設身份驗證選項。The new dialog enables you to change the default authentication options for many of the templates. 例如,在建立ASP.NET Web 窗體專案時,您可以選擇以下任一選項:For example, when you create an ASP.NET Web Forms project you can select any of the following options:

  • 不需要驗證No Authentication
  • 個人使用者帳戶(ASP.NET會員身份或社交提供者登入)Individual User Accounts (ASP.NET membership or social provider log in)
  • 組織帳號 (網路應用程式中的活動目錄)Organizational Accounts (Active Directory in an internet application)
  • Windows 驗證(Intranet 應用程式中的活動目錄)Windows Authentication (Active Directory in an intranet application)

驗證選項

有關建立 Web 專案的新流程的詳細資訊,請參閱在Visual Studio 2013 建立 ASP.NET Web 專案For more information about the new process for creating web projects, see Creating ASP.NET Web Projects in Visual Studio 2013. 關於新身份驗證選項的詳細資訊,請參考此文件後面的ASP.NET 識別For more information about the new authentication options, see ASP.NET Identity later in this document.

ASP.NET腳手架ASP.NET Scaffolding

ASP.NET基架是ASP.NET Web 應用程式的代碼生成框架。ASP.NET Scaffolding is a code generation framework for ASP.NET Web applications. 它可以輕鬆地向與數據模型交互的專案添加樣板代碼。It makes it easy to add boilerplate code to your project that interacts with a data model.

在 Visual Studio 的早期版本中,基架僅限於 ASP.NET MVC 專案。In previous versions of Visual Studio, scaffolding was limited to ASP.NET MVC projects. 借助 Visual Studio 2013,您現在可以對任何 ASP.NET 專案(包括 Web 窗體)使用基架。With Visual Studio 2013, you can now use scaffolding for any ASP.NET project, including Web Forms. Visual Studio 2013 目前不支援為 Web 窗體專案生成頁面,但您仍可以通過向專案添加 MVC 依賴項來使用 Web 窗體的腳手架。Visual Studio 2013 does not currently support generating pages for a Web Forms project, but you can still use scaffolding with Web Forms by adding MVC dependencies to the project. 將在將來的更新中添加對生成 Web 窗體頁面的支援。Support for generating pages for Web Forms will be added in a future update.

使用基架時,我們確保在專案中安裝了所有必需的依賴項。When using scaffolding, we ensure that all required dependencies are installed in the project. 例如,如果從ASP.NET Web 窗體專案開始,然後使用基架添加 Web API 控制器,則所需的 NuGet 包和引用將自動添加到專案中。For example, if you start with an ASP.NET Web Forms project and then use scaffolding to add a Web API Controller, the required NuGet packages and references are added to your project automatically.

要將 MVC 基架加入 Web 窗體專案,請新增新的文手架, 並在對話框視窗中選擇MVC 5 相依項 。To add MVC scaffolding to a Web Forms project, add a New Scaffolded Item and select MVC 5 Dependencies in the dialog window. 基架 MVC 有兩個選項;最小和完整。There are two options for scaffolding MVC; Minimal and Full. 如果選擇「最小」,則只有 ASP.NET MVC 的 NuGet 包和引用添加到專案中。If you select Minimal, only the NuGet packages and references for ASP.NET MVC are added to your project. 如果選擇"完整"選項,則添加最小依賴項以及 MVC 專案所需的內容檔。If you select the Full option, the Minimal dependencies are added, as well as the required content files for an MVC project.

支援基架非同步控制器使用實體框架6中的新異步功能。Support for scaffolding async controllers uses the new async features from Entity Framework 6.

有關詳細資訊和教程,請參閱ASP.NET 腳手架概述For more information and tutorials, see ASP.NET Scaffolding Overview.

新的瀏覽器連結功能允許您將多個瀏覽器連接到 Visual Studio,並透過單擊工具列中的按鈕刷新所有瀏覽器。The new Browser Link feature lets you connect multiple browsers to Visual Studio and refresh them all by clicking a button in the toolbar. 您可以將多個瀏覽器連接到開發網站(包括移動模擬程式),然後單擊刷新以同時刷新所有瀏覽器。You can connect multiple browsers to your development site, including mobile emulators, and click refresh to refresh all the browsers all at the same time. 瀏覽器連結還公開 API,使開發人員能夠編寫瀏覽器連結擴展。Browser Link also exposes an API to enable developers to write Browser Link extensions.

通過使開發人員能夠利用瀏覽器連結 API,可以創建非常高級的方案,這些方案跨越 Visual Studio 和任何已連接的瀏覽器之間的邊界。By enabling developers to take advantage of the Browser Link API, it becomes possible to create very advanced scenarios that crosses boundaries between Visual Studio and any browser that's connected. Web Essentials 利用 API 在 Visual Studio 和瀏覽器的開發人員工具、遠端控制行動模擬器等之間創建整合體驗。Web Essentials takes advantage of the API to create an integrated experience between Visual Studio and the browser's developer tools, remote controlling mobile emulators and a lot more.

視覺化工作室 Web 編輯器增強功能Visual Studio Web Editor Enhancements

Visual Studio 2013 包括用於 Web 應用程式中 Razor 檔案和 HTML 檔案的新 HTML 編輯器。Visual Studio 2013 includes a new HTML editor for Razor files and HTML files in web applications. 新的 HTML 編輯器提供基於 HTML5 的單一架構。The new HTML editor provides a single unified schema based on HTML5. 它有自動大括弧完成,jQuery UI和AngularJS屬性IntelliSense,屬性IntelliSense分組,ID和類名Intellisense,和其他改進,包括更好的性能,格式和智慧標籤。It has automatic brace completion, jQuery UI and AngularJS attribute IntelliSense, attribute IntelliSense Grouping, ID and class name Intellisense, and other improvements including better performance, formatting and SmartTags.

以下螢幕截圖示範如何在 HTML 編輯器中使用 Bootstrap 屬性 IntelliSense。The following screenshot demonstrates using Bootstrap attribute IntelliSense in the HTML editor.

HTML 編輯器中的感知

Visual Studio 2013 還附帶了內置的咖啡腳本和 LESS 編輯器。Visual Studio 2013 also comes with both CoffeeScript and LESS editors built in. LESS 編輯器附帶了 CSS 編輯器中的所有很酷的功能,@import並具有針對鏈中所有 LESS 文件中的變數和混合值的特定 Intellisense。The LESS editor comes with all the cool features from the CSS editor and has specific Intellisense for variables and mixins across all the LESS documents in the @import chain.

Visual Studio 中的 Azure 應用服務 Web 應用支援Azure App Service Web Apps Support in Visual Studio

在 Visual Studio 2013 中,使用用於 .NET 2.2 的 Azure SDK,可以使用伺服器資源管理器直接與遠端 Web 應用進行交互。In Visual Studio 2013 with the Azure SDK for .NET 2.2, you can use Server Explorer to interact directly with your remote web apps. 您可以登錄到 Azure 帳戶、創建新的 Web 應用、配置應用、查看即時日誌等。You can sign in to your Azure account, create new web apps, configure apps, view real-time logs, and more. SDK 2.2 發佈後不久,您將能夠在 Azure 中遠端在調試模式下運行。Coming soon after SDK 2.2 is released, you'll be able to run in debug mode remotely in Azure. 安裝 .NET 的 Azure SDK 當前版本時,Azure 應用服務 Web 應用的大多數新功能在 Visual Studio 2012 中也起作用。Most of the new features for Azure App Service Web Apps also work in Visual Studio 2012 when you install the current release of the Azure SDK for .NET.

如需詳細資訊,請參閱下列資源:For more information, see the following resources:

Web 發佈增強功能Web Publish Enhancements

Visual Studio 2013 包括新的和增強的 Web 發佈功能。Visual Studio 2013 includes new and enhanced Web Publish features. 以下提供其中一些範例:Here are a few of them:

有關ASP.NET Web 部署的詳細資訊,請參閱ASP.NET網站For more information about ASP.NET web deployment, see the ASP.NET site.

NuGet 2.7NuGet 2.7

NuGet 2.7 包含一組豐富的新功能,在NuGet 2.7 發行說明中對此進行了詳細介紹。NuGet 2.7 includes a rich set of new features which are described in detail at NuGet 2.7 Release Notes.

此版本的 NuGet 還無需為 NuGet 的包還原功能提供下載包的明確同意。This version of NuGet also removes the need to provide explicit consent for NuGet's package restore feature to download packages. 現在透過安裝 NuGet 授予同意(以及 NuGet 首選項對話方塊中的關聯複選框)。Consent (and the associated checkbox in NuGet's preferences dialog) is now granted by installing NuGet. 現在,默認情況下,包還原只是工作。Now package restore simply works by default.

ASP.NET Web FormsASP.NET Web Forms

一ASP.NETOne ASP.NET

Web 窗體專案範本與新 one ASP.NET 體驗無縫集成。The Web Forms project templates integrate seamlessly with the new One ASP.NET experience. 您可以將 MVC 和 Web API 支援添加到 Web 窗體專案中,並且可以使用「一ASP.NET專案創建嚮導設定身份驗證。You can add MVC and Web API support to your Web Forms project, and you can configure authentication using the One ASP.NET project creation wizard. 有關詳細資訊,請參閱在Visual Studio 2013 中建立 ASP.NET Web 專案For more information, see Creating ASP.NET Web Projects in Visual Studio 2013.

ASP.NET IdentityASP.NET Identity

Web 表單樣專案樣本支援新的ASP.NET識別架構。The Web Forms project templates support the new ASP.NET Identity framework. 此外,範本現在支援創建 Web 窗體 Intranet 專案。In addition, the templates now support creation of a Web Forms intranet project. 有關詳細資訊,請參閱在Visual Studio 2013 中建立 ASP.NET Web 專案的認證方法For more information, see Authentication Methods in Creating ASP.NET Web Projects in Visual Studio 2013.

啟動程序Bootstrap

Web 表單表板使用Bootstrap提供時尚且回應迅速的外觀,讓您輕鬆自定義。The Web Forms templates use Bootstrap to provide a sleek and responsive look and feel that you can easily customize. 有關詳細資訊,請參閱Visual Studio 2013 Web 專案範本中的 Bootstrap。For more information, see Bootstrap in the Visual Studio 2013 web project templates.

ASP.NET MVC 5ASP.NET MVC 5

一ASP.NETOne ASP.NET

Web MVC 專案範本與新一ASP.NET體驗無縫整合。The Web MVC project templates integrate seamlessly with the new One ASP.NET experience. 您可以使用「一ASP.NET項目創建嚮導自定義 MVC 專案並設定身份驗證。You can customize your MVC project and configure authentication using the One ASP.NET project creation wizard. ASP.NET MVC 5 的入門教程可以在ASP.NET MVC 5 入門中找到。An introductory tutorial to ASP.NET MVC 5 can be found at Getting Started with ASP.NET MVC 5.

有關將 MVC 4 專案升級到 MVC 5 的資訊,請參閱如何將 ASP.NET MVC 4 和 Web API 專案升級到 ASP.NET MVC 5 和 Web API 2For information on upgrading MVC 4 projects to MVC 5, see How to Upgrade an ASP.NET MVC 4 and Web API Project to ASP.NET MVC 5 and Web API 2.

ASP.NET IdentityASP.NET Identity

MVC 專案範本已更新,用於ASP.NET標識進行身份驗證和標識管理。The MVC project templates have been updated to use ASP.NET Identity for authentication and identity management. 一個教程,包括Facebook和谷歌認證和新的會員API可以在創建ASP.NETMVC 5應用程式與Facebook和谷歌OAuth2和OpenID登錄,並建立ASP.NETMVC應用程式與auth和SQL DB,並部署到Azure應用程式服務A tutorial featuring Facebook and Google authentication and the new membership API can be found at Create an ASP.NET MVC 5 App with Facebook and Google OAuth2 and OpenID Sign-on and Create an ASP.NET MVC app with auth and SQL DB and deploy to Azure App Service.

啟動程序Bootstrap

MVC 專案範本已更新,可使用Bootstrap提供時尚且回應迅速的外觀,讓您輕鬆自定義。The MVC project template has been updated to use Bootstrap to provide a sleek and responsive look and feel that you can easily customize. 有關詳細資訊,請參閱Visual Studio 2013 Web 專案範本中的 Bootstrap。For more information, see Bootstrap in the Visual Studio 2013 web project templates.

驗證篩選器Authentication filters

身份驗證篩選器是 ASP.NET MVC 中一種新型篩選器,在 ASP.NET MVC 管道中的授權篩選器之前運行,允許您為所有控制器指定每個操作、每個控制器或全域的身份驗證邏輯。Authentication filters are a new kind of filter in ASP.NET MVC that run prior to authorization filters in the ASP.NET MVC pipeline and allow you to specify authentication logic per-action, per-controller, or globally for all controllers. 身份驗證篩選器處理請求中的憑據並提供相應的主體。Authentication filters process credentials in the request and provide a corresponding principal. 身份驗證篩選器還可以添加身份驗證質詢以回應未經授權的請求。Authentication filters can also add authentication challenges in response to unauthorized requests.

篩選器覆寫Filter overrides

現在,可以通過指定覆蓋篩選器來覆蓋應用於給定操作方法或控制器的篩選器。You can now override which filters apply to a given action method or controller by specifying an override filter. 覆蓋篩選器指定一組不應為給定作用域(操作或控制器)運行的篩選器類型。Override filters specify a set of filter types that should not be run for a given scope (action or controller). 這允許您配置全域應用的篩選器,但隨後排除某些全域篩選器應用於特定操作或控制器。This allows you to configure filters that apply globally but then exclude certain global filters from applying to specific actions or controllers.

屬性路由Attribute routing

ASP.NET MVC 現在支援屬性路由,這要歸http://attributerouting.net功於 Tim McCall(作者)的貢獻。ASP.NET MVC now supports attribute routing, thanks to a contribution by Tim McCall, the author of http://attributerouting.net. 使用屬性路由,您可以通過對操作和控制器進行說明來指定路由。With attribute routing you can specify your routes by annotating your actions and controllers.

ASP.NET Web API 2ASP.NET Web API 2

屬性路由Attribute routing

ASP.NET Web API 現在支援屬性路由,這要http://attributerouting.net歸功於 Tim McCall(作者)的貢獻。ASP.NET Web API now supports attribute routing, thanks to a contribution by Tim McCall, the author of http://attributerouting.net. 使用屬性路由,您可以通過指定操作和控制器來指定 Web API 路由,如下所示:With attribute routing you can specify your Web API routes by annotating your actions and controllers like this:

[RoutePrefix("orders")] 
public class OrdersController : ApiController 
{ 
    [Route("{id}")] 
    public Order Get(int id) { } 
    [Route("{id}/approve")] 
    public Order Approve(int id) { } 
}

屬性路由使您能夠對 Web API 中的 URI 進行更多控制。Attribute routing gives you more control over the URIs in your web API. 例如,您可以使用單個 API 控制器輕鬆定義資源層次結構:For example, you can easily define a resource hierarchy using a single API controller:

public class MoviesController : ApiController 
{ 
    [Route("movies")] 
    public IEnumerable<Movie> Get() { } 
    [Route("actors/{actorId}/movies")] 
    public IEnumerable<Movie> GetByActor(int actorId) { } 
    [Route("directors/{directorId}/movies")] 
    public IEnumerable<Movie> GetByDirector(int directorId) { } 
}

屬性路由還提供用於指定可選參數、預設值和路由約束的便捷語法:Attribute routing also provides a convenient syntax for specifying optional parameters, default values, and route constraints:

// Optional parameter
[Route("people/{name?}")]
// Default value
[Route("people/{name=Dan}")]
// Constraint: Alphabetic characters only. 
[Route("people/{name:alpha}")]

有關屬性路由的詳細資訊,請參閱Web API 2 中的屬性路由For more information about attribute routing, see Attribute Routing in Web API 2.

OAuth 2.0OAuth 2.0

Web API 和單頁應用程式專案範本現在支援使用 OAuth 2.0 進行授權。The Web API and Single Page Application project templates now support authorization using OAuth 2.0. OAuth 2.0 是一個用於授權客戶端訪問受保護資源的框架。OAuth 2.0 is a framework for authorizing client access to protected resources. 它適用於各種用戶端,包括瀏覽器和行動裝置。It works for a variety of clients including browsers and mobile devices.

對 OAuth 2.0 的支援基於 Microsoft OWIN 元件為承載身份驗證和實現授權伺服器角色而提供的新安全中間件。Support for OAuth 2.0 is based on new security middleware provided by the Microsoft OWIN Components for bearer authentication and implementing the authorization server role. 或者,可以使用組織授權伺服器(如 Windows Server 2012 R2 中的 Azure 活動目錄或 ADFS)授權用戶端。Alternatively, clients can be authorized using an organizational authorization server, such as Azure Active Directory or ADFS in Windows Server 2012 R2.

O 資料改進OData Improvements

支援$select、$expand、$batch和$valueSupport for $select, $expand, $batch, and $value

ASP.NET Web API OData 現在完全支援$select、$expand和$value。ASP.NET Web API OData now has full support for $select, $expand, and $value. 您還可以使用$batch請求批處理和處理更改集。You can also use $batch for request batching and processing of change sets.

$select和$expand選項允許您更改從 OData 終結點傳回的數據的形狀。The $select and $expand options let you change the shape of the data that is returned from an OData endpoint. 有關詳細資訊,請參閱在Web API OData 中介紹$select 和$expand支援For more information, see Introducing $select and $expand support in Web API OData.

提高可擴充性Improved extensibility

OData for 物質現在可擴展。The OData formatters are now extensible. 您可以添加 Atom 條目元數據、支援命名串流和媒體連結項目、添加實例註釋以及自訂連結的生成方式。You can add Atom entry metadata, support named stream and media link entries, add instance annotations, and customize how links are generated.

沒有類型支援Type-less support

現在,您可以構建 OData 服務,而無需為實體類型定義 CLR 類型。You can now build OData services without needing to define CLR types for your entity types. 相反,您的 OData 控制器可以獲取或返回IEdmObject的實例 ,這是用於序列化/反序列化的 OData 實例。Instead, your OData controllers can take or return instances of IEdmObject, which are the OData formatters serialize/deserialize.

重用現有模型Reuse an existing model

如果您已有現有的實體數據模型 (EDM),現在可以直接重用它,而不必構建新的實體數據模型。If you already have an existing entity data model (EDM), you can now reuse it directly, instead of having to build a new one. 例如,如果您使用的是實體框架,則可以使用 EF 為您生成的 EDM。For example, if you are using Entity Framework, you can use the EDM that EF builds for you.

要求處理Request Batching

請求批處理將多個操作合併到單個 HTTP POST 請求中,以減少網路流量並提供更順暢、更不健談的使用者介面。Request batching combines multiple operations into a single HTTP POST request, to reduce network traffic and provide a smoother, less chatty user interface. ASP.NET Web API 現在支援幾種要求批次處理策略:ASP.NET Web API now supports several strategies for request batching:

  • 使用 OData 服務$batch終結點。Use the $batch endpoint of an OData service.
  • 將多個請求打包到單個 MIME 多部分請求中。Package multiple requests into a single MIME multipart request.
  • 使用自定義批處理格式。Use a custom batching format.

要啟用要求批次處理,只需將具有批次處理處理程式的路由新增到 Web API 設定中:To enable request batching, simply add a route with a batching handler to your Web API configuration:

public static class WebApiConfig 
{ 
    public static void Register(HttpConfiguration config) 
    { 
        config.Routes.MapHttpBatchRoute( 
            routeName: "WebApiBatch", 
            routeTemplate: "api/batch", 
            batchHandler: new DefaultHttpBatchHandler(GlobalConfiguration.DefaultServer)); 
    } 
}

您還可以控制請求或按順序執行,還是按任何順序執行。You can also control whether requests or executed sequentially or in any order.

可移植ASP.NET Web API 用戶端Portable ASP.NET Web API Client

現在,可以使用ASP.NET Web API 用戶端創建跨 Windows 應用商店和 Windows Phone 8 應用程式的便攜式類庫。You can now use the ASP.NET Web API Client to create portable class libraries that work across your Windows Store and Windows Phone 8 applications. 您還可以創建可在用戶端和伺服器之間共用的可移植的要件。You can also create portable formatters that can be shared across client and server.

提高可測試性Improved Testability

Web API 2 使單元測試 API 控制器變得更加容易。Web API 2 makes it much easier to unit test your API controllers. 只需使用請求消息和配置實例化 API 控制器,然後調用要測試的操作方法。Just instantiate your API controller with your request message and configuration, and then call the action method you wish to test. 對於執行連結生成的操作方法,也很容易類比UrlHelper類。It is also easy to mock the UrlHelper class, for action methods that perform link generation.

IHTTPAction 結果IHttpActionResult

現在,您可以實現 IHttpActionResult 來封裝 Web API 操作方法的結果。You can now implement IHttpActionResult to encapsulate the result of your Web API action methods. 從 Web API 操作方法傳回的 IHttpActionResult 由 ASP.NET Web API 執行時執行,以生成產生的回應消息。An IHttpActionResult returned from a Web API action method is executed by the ASP.NET Web API runtime to produce the resultant response message. 可以從任何 Web API 操作傳回 IHttpActionResult,以簡化 Web API 實現單元測試。An IHttpActionResult can be returned from any Web API action to simplify unit testing of your Web API implementation. 為方便起見,一些IHttpActionResult實現在開箱即用,包括用於返回特定狀態代碼、格式化內容或內容協商回應的結果。For convenience a number of IHttpActionResult implementations are provided out of the box including results for returning specific status codes, formatted content or content-negotiated responses.

HTTPRequestContextHttpRequestContext

新的HttpRequestContext追蹤與請求關聯的任何狀態,但無法立即從請求中獲取。The new HttpRequestContext tracks any state that is tied to the request but is not immediately available from the request. 例如,可以使用HttpRequestContext獲取路由資料、與請求關聯的主體、用戶端證書 、UrlHelper和虛擬路徑根。For example, you can use the HttpRequestContext to get route data, the principal associated with the request, the client certificate, the UrlHelper and the virtual path root. 您可以輕鬆地為單元測試目的創建HTTPRequestContext。You can easily create an HttpRequestContext for unit testing purposes.

由於請求的主體隨請求一起流動,而不是依賴於Thread.CurrentThe, 因此主體現在在請求在 Web API 管道中時在請求的整個生存期內可用。Because the principal for the request is flowed with the request instead of relying on Thread.CurrentPrincipal, the principal is now available throughout the lifetime of the request while it is in the Web API pipeline.

CORSCORS

多虧了布羅克·艾倫的另一個巨大貢獻,ASP.NET現在完全支援跨原請求共用 (CORS)。Thanks to another great contribution from Brock Allen, ASP.NET now fully supports Cross Origin Request Sharing (CORS).

瀏覽器安全性可防止網頁對另一個網域提出 AJAX 要求。Browser security prevents a web page from making AJAX requests to another domain. CORS是一種 W3C 標準,允許伺服器放鬆同源策略。CORS is a W3C standard that allows a server to relax the same-origin policy. 使用 CORS,伺服器可以明確允許某些跨源要求,然而拒絕其他要求。Using CORS, a server can explicitly allow some cross-origin requests while rejecting others.

Web API 2 現在支援 CORS,包括自動處理預檢請求。Web API 2 now supports CORS, including automatic handling of preflight requests. 如需詳細資訊,請參閱 在 ASP.NET Web API 中啟用跨原始來源要求For more information, see Enabling Cross-Origin Requests in ASP.NET Web API.

驗證篩選器Authentication Filters

驗證篩選器是 web API 中 ASP.NET 一種新型篩選器,在 ASP.NET Web API 管道中授權篩選器之前運行,允許您為所有控制器指定每個操作、每個控制器或全域的身份驗證邏輯。Authentication filters are a new kind of filter in ASP.NET Web API that run prior to authorization filters in the ASP.NET Web API pipeline and allow you to specify authentication logic per-action, per-controller, or globally for all controllers. 身份驗證篩選器處理請求中的憑據並提供相應的主體。Authentication filters process credentials in the request and provide a corresponding principal. 身份驗證篩選器還可以添加身份驗證質詢以回應未經授權的請求。Authentication filters can also add authentication challenges in response to unauthorized requests.

篩選器覆寫Filter Overrides

現在,可以通過指定重寫篩選器來覆蓋應用於給定操作方法或控制器的篩選器。You can now override which filters apply to a given action method or controller, by specifying an override filter. 覆蓋篩選器指定一組不應為給定作用域(操作或控制器)運行的篩選器類型。Override filters specify a set of filter types that should not run for a given scope (action or controller). 這允許您添加全域篩選器,但隨後從特定操作或控制器中排除某些篩選器。This allows you to add global filters, but then exclude some from specific actions or controllers.

OWIN 整合OWIN Integration

ASP.NET Web API 現在完全支援 OWIN,可以在任何支援 OWIN 的主機上運行。ASP.NET Web API now fully supports OWIN and can be run on any OWIN capable host. 還包括一個主機身份驗證篩選器,它提供與 OWIN 身份驗證系統的集成。Also included is a HostAuthenticationFilter that provides integration with the OWIN authentication system.

通過 OWIN 整合,您可以與其他 OWIN 中間件(如 SignalR)一起,在您自己的進程中自行託管 Web API。With OWIN integration, you can self-host Web API in your own process alongside other OWIN middleware, such as SignalR. 有關詳細資訊,請參閱使用OWIN ASP.NET Web API 進行自託管For more information, see Use OWIN to Self-Host ASP.NET Web API.

ASP.NET信號R 2.0ASP.NET SignalR 2.0

以下各節介紹 SignalR 2.0 的功能。The following sections describe features of SignalR 2.0.

有關如何將現有的 1.x 專案升級到 SignalR 2.0 的範例,請參閱升級 SignalR 1.x 專案For an example of how to upgrade an existing 1.x project to SignalR 2.0, see Upgrading a SignalR 1.x Project.

基於 OWIN 建譯Built on OWIN

SignalR 2.0 完全基於OWIN(.NET 的開放 Web 介面)構建。SignalR 2.0 is built completely on OWIN (the Open Web Interface for .NET). 此更改使 SignalR 的設定過程在 Web 託管和自託管 SignalR 應用程式之間更加一致,但還需要多次 API 更改。This change makes the setup process for SignalR much more consistent between web-hosted and self-hosted SignalR applications, but has also required a number of API changes.

地圖集線與地圖連線現在是對應訊號MapHubs and MapConnection are now MapSignalR

為了與 OWIN 標準相容,這些方法已重新MapSignalR命名為 。For compatibility with OWIN standards, these methods have been renamed to MapSignalR. MapSignalR在沒有參數的情況下調用將映射所有中心(如MapHubs版本1.x);映射單個持久連接物件,將連接類型指定為類型參數,並將連接的 URL 擴展作為第一個參數。MapSignalR called without parameters will map all hubs (as MapHubs does in version 1.x); to map individual PersistentConnection objects, specify the connection type as the type parameter, and the URL extension for the connection as the first argument.

該方法MapSignalR在 Owin 啟動類中調用。The MapSignalR method is called in an Owin startup class. Visual Studio 2013 包含 Owin 啟動類的新範本;要使用此樣本,請使用以下操作:Visual Studio 2013 contains a new template for an Owin startup class; to use this template, do the following:

  1. 右鍵單擊項目Right-click on the project
  2. 選擇 '新增****',新專案...Select Add, New Item...
  3. 選擇Owin 啟動類別Select Owin Startup class. Startup.cs命名新類。Name the new class Startup.cs.

Web 應用程式中,MapSignalR包含該方法 的 Owin 啟動類別後使用 Web.Config 檔的應用程式設定節點中的條目添加到 Owin 的啟動過程中,如下所示。In a Web application, the Owin startup class containing the MapSignalR method is then added to Owin's startup process using an entry in the application settings node of the Web.Config file, as shown below.

自託管應用程式中,啟動類作為WebApp.Start方法的類型參數傳遞。In a Self-hosted application, the Startup class is passed as the type parameter of the WebApp.Start method.

映射 SignalR 1.x 中的集線器與連線(來自 Web 應用程式中的全域應用程式檔案):Mapping hubs and connections in SignalR 1.x (from the global application file in a web application):

protected void Application_Start(object sender, EventArgs e) 
{
    // Map all hubs to "/signalr"
    RouteTable.Routes.MapHubs();
    // Map the Echo PersistentConnection to "/echo"
    RouteTable.Routes.MapConnection<myconnection>("echo", "/echo");
}

映射 SignalR 2.0 中的集線器與連線(來自 Owin 啟動類別):Mapping hubs and connections in SignalR 2.0 (from an Owin Startup class file):

using Microsoft.AspNet.SignalR;
using Microsoft.Owin;
using Owin;

[assembly: OwinStartup(typeof(MyWebApplication.Startup))]

namespace MyWebApplication
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            // Map all hubs to "/signalr"
            app.MapSignalR();
            // Map the Echo PersistentConnection to "/echo"
            app.MapSignalR<echoconnection>("/echo");
        }
    }
}

自託管應用程式中,啟動類WebApp.Start作為 方法的類型參數傳遞,如下所示。In a Self-hosted application, the Startup class is passed as the type parameter for the WebApp.Start method, as shown below.

string url = "http://localhost:8080";
using (WebApp.Start<startup>(url))
{
    Console.WriteLine("Server running on {0}", url);
    Console.ReadLine();
}

跨域支援Cross-Domain Support

在 SignalR 1.x 中,跨域請求由單個啟用 CrossDomain 標誌控制。In SignalR 1.x, cross domain requests were controlled by a single EnableCrossDomain flag. 此標誌同時控制 JSONP 和 CORS 請求。This flag controlled both JSONP and CORS requests. 為了更靈活,所有 CORS 支援都從 SignalR 的伺服器元件中刪除(如果檢測到瀏覽器支援它,JAVAScript 用戶端仍通常使用 CORS),並且新的 OWIN 中間件已可用於支援這些方案。For greater flexibility, all CORS support has been removed from the server component of SignalR (JavaScript clients still use CORS normally if it is detected that the browser supports it), and new OWIN middleware has been made available to support these scenarios.

在 SignalR 2.0 中,如果用戶端上需要 JSONP(以支援舊瀏覽器中的跨域請求),EnableJSONP``HubConfigurationtrue需要通過在 物件 上設置為 (如下所示)顯式啟用它。In SignalR 2.0, If JSONP is required on the client (to support cross-domain requests in older browsers), it will need to be enabled explicitly by setting EnableJSONP on the HubConfiguration object to true, as shown below. 默認情況下禁用 JSONP,因為它的安全性低於 CORS。JSONP is disabled by default, as it is less secure than CORS.

要在 SignalR 2.0 中添加Microsoft.Owin.Cors新的 CORS 中間件,UseCors請將庫添加到 專案中,並在 SignalR 中間件之前調用,如下節所示。To add the new CORS middleware in SignalR 2.0, add the Microsoft.Owin.Cors library to your project, and call UseCors before your SignalR middleware, as shown in the section below.

將 Microsoft.Owin.Cors 新增到您的專案:要安裝此庫,請在套件管理員控制台中執行以下指令:Adding Microsoft.Owin.Cors to your project: To install this library, run the following command in the Package Manager Console:

Install-Package Microsoft.Owin.Cors

此命令會將包的 2.0.0 版本添加到專案中。This command will add the 2.0.0 version of the package to your project.

呼叫使用參數Calling UseCors

以下代碼段演示如何在 SignalR 1.x 和 2.0 中實現跨域連接。The following code snippets demonstrate how to implement cross-domain connections in SignalR 1.x and 2.0.

在 SignalR 1.x 中實現跨網域要求 (來自全域應用程式檔案)Implementing cross-domain requests in SignalR 1.x (from the global application file)

protected void Application_Start(object sender, EventArgs e) 
{
    var hubConfiguration = new HubConfiguration();
    hubConfiguration.EnableCrossDomain = true;
    RouteTable.Routes.MapHubs(hubConfiguration);
}

在 SignalR 2.0 中實現跨網域要求 (來自 C# 代碼檔案)Implementing cross-domain requests in SignalR 2.0 (from a C# code file)

以下代碼展示如何在 SignalR 2.0 專案中啟用 CORS 或 JSONP。The following code demonstrates how to enable CORS or JSONP in a SignalR 2.0 project. 此代碼示例使用Map``RunSignalR``MapSignalR而不是 ,以便 CORS 中間件僅運行需要 CORS 支援的 SignalR 請求(而不是針對中MapSignalR指定的路徑上的所有流量)。Map還可用於需要為特定 URL 首碼運行的任何其他中間件,而不是整個應用程式。This code sample uses Map and RunSignalR instead of MapSignalR, so that the CORS middleware runs only for the SignalR requests that require CORS support (rather than for all traffic at the path specified in MapSignalR.) Map can also be used for any other middleware that needs to run for a specific URL prefix, rather than for the entire application.

using Microsoft.AspNet.SignalR;
using Microsoft.Owin.Cors;
using Owin;

[assembly: OwinStartup(typeof(MyWebApplication.Startup))]

namespace MyWebApplication
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            // Branch the pipeline here for requests that start with "/signalr"
            app.Map("/signalr", map =>
            {
                // Setup the CORS middleware to run before SignalR.
                // By default this will allow all origins. You can 
                // configure the set of origins and/or http verbs by
                // providing a cors options with a different policy.
                map.UseCors(CorsOptions.AllowAll);
                var hubConfiguration = new HubConfiguration 
                {
                    // You can enable JSONP by uncommenting line below.
                    // JSONP requests are insecure but some older browsers (and some
                    // versions of IE) require JSONP to work cross domain
                    // EnableJSONP = true
                };
                // Run the SignalR pipeline. We're not using MapSignalR
                // since this branch already runs under the "/signalr"
                // path.
                map.RunSignalR(hubConfiguration);
            });
        }
    }
}

透過單點觸控和單體機器人支援 iOS 和 AndroidiOS and Android support via MonoTouch and MonoDroid

已使用Xamarin 庫中的 MonoTouch 和 MonoDroid 元件為 iOS 和 Android 用戶端添加了支援。Support has been added for iOS and Android clients using MonoTouch and MonoDroid components from the Xamarin library. 有關如何使用它們的詳細資訊,請參閱使用 Xamarin 元件For more information on how to use them, see Using Xamarin Components. 當 SignalR RTW 版本可用時,這些元件將在Xamarin 儲存中可用。These components will be available in the Xamarin Store when the SignalR RTW release is available.

• 可移植 .NET 用戶端### Portable .NET client

為了更好地促進跨平台開發,Silverlight、WinRT 和 Windows Phone 用戶端已替換為支援以下平臺的單個可攜式 .NET 用戶端:To better facilitate cross-platform development, the Silverlight, WinRT and Windows Phone clients have been replaced with a single portable .NET client that supports the following platforms:

  • 淨 4.5NET 4.5
  • Silverlight 5Silverlight 5
  • WinRT (.NET 用於 Windows 應用商店應用)WinRT (.NET for Windows Store Apps)
  • Windows Phone 8Windows Phone 8

新的自主機包New Self-Host Package

現在有一個 NuGet 套件,以便更輕鬆地開始使用 SignalR 自主機(託管在行程或其他應用程式中的 SignalR 應用程式,而不是託管在 Web 伺服器中)。There is now a NuGet package to make it easier to get started with SignalR Self-Host (SignalR applications that are hosted in a process or other application, rather than being hosted in a web server). 要升級使用 SignalR 1.x 構建的自主機專案,請刪除 Microsoft.AspNet.SignalR.Owin 包,然後添加 Microsoft.AspNet.SignalR.SelfHost 包。To upgrade a self-host project built with SignalR 1.x, remove the Microsoft.AspNet.SignalR.Owin package, and add the Microsoft.AspNet.SignalR.SelfHost package. 有關開始使用自主機包的詳細資訊,請參閱教程:SignalR 自主機For more information on getting started with the self-host package, see Tutorial: SignalR Self-Host.

向後相容的伺服器支援Backward-compatible server support

在早期版本的 SignalR 中,用戶端和伺服器中使用的 SignalR 套件版本需要相同。In previous versions of SignalR, the versions of the SignalR package used in the client and the server needed to be identical. 為了支援難以更新的粗用戶端應用程式,SignalR 2.0 現在支援使用較新的伺服器版本與較舊的用戶端。In order to support thick-client applications that would be difficult to update, SignalR 2.0 now supports using a newer server version with an older client. 注意:SignalR 2.0 不支援使用較舊版本的較舊用戶端構建的伺服器。Note: SignalR 2.0 does not support servers built with older versions with newer clients.

已移除此.NET 4.0 的伺服器支援Removed server support for .NET 4.0

SignalR 2.0 已放棄對伺服器與 .NET 4.0 的互通性的支援。SignalR 2.0 has dropped support for server interoperability with .NET 4.0. .NET 4.5 必須與 SignalR 2.0 伺服器一起使用。.NET 4.5 must be used with SignalR 2.0 servers. 信號R 2.0 仍有 .NET 4.0 用戶端。There is still a .NET 4.0 client for SignalR 2.0.

將訊息傳送到客戶端及群組清單Sending a message to a list of clients and groups

在 SignalR 2.0 中,可以使用用戶端和組 IT 的清單發送消息。In SignalR 2.0, it's possible to send a message using a list of client and group IDs. 以下代碼段演示如何執行此操作。The following code snippets demonstrate how to do this.

使用持久連線將訊息傳送到客戶端及群組清單Sending a message to a list of clients and groups using PersistentConnection

using Microsoft.AspNet.SignalR;
using System.Collections.Generic;
public class ChatConnection : PersistentConnection
{
    static List<string> ConnectionIds = new List<string>();
    static List<string> groups = new List<string>{"chatGroup", "chatGroup2"};
    protected override System.Threading.Tasks.Task OnReceived(IRequest request, string connectionId, string data)
    {
        Connection.Send(ConnectionIds, data);
        Groups.Send(groups, data);
        return base.OnReceived(request, connectionId, data);
    }
    protected override System.Threading.Tasks.Task OnConnected(IRequest request, string connectionId)
    {
        ConnectionIds.Add(connectionId);
        Groups.Add(connectionId, "chatGroup");
        return base.OnConnected(request, connectionId);
    }
    protected override System.Threading.Tasks.Task OnDisconnected(IRequest request, string connectionId)
    {
        ConnectionIds.Remove(connectionId);
        return base.OnDisconnected(request, connectionId);
    }
}

使用中心向客戶端及群組清單傳送訊息Sending a message to a list of clients and groups using Hubs

using Microsoft.AspNet.SignalR;
using System.Collections.Generic;
public class ChatHub : Hub
{
    static List<string> ConnectionIds = new List<string>();
    static List<string> groups = new List<string> { "chatGroup", "chatGroup2" };
    public void Send(string name, string message)
    {
        // Call the broadcastMessage method to update clients.
        Clients.Clients(ConnectionIds).broadcastMessage(name, message);
        Clients.Groups(groups).broadcastMessage(name, message);
    }
    public override System.Threading.Tasks.Task OnConnected()
    {
        ConnectionIds.Add(Context.ConnectionId);
        Groups.Add(Context.ConnectionId, "chatGroup");
        return base.OnConnected();
    }
    public override System.Threading.Tasks.Task OnDisconnected()
    {
        ConnectionIds.Remove(Context.ConnectionId);
        return base.OnDisconnected();
    }
}

傳送使用者傳送訊息Sending a message to a specific user

此功能允許使用者透過新介面 IUserIdProvider 指定使用者 Id 基於 IRequest 的內容:This feature allows users to specify what the userId is based on an IRequest via a new interface IUserIdProvider:

IUserId 提供者介面The IUserIdProvider interface

public interface IUserIdProvider
{
    string GetUserId(IRequest request);
}

默認情況下,將有一個使用使用者IPrincipal.Identity.Name作為使用者名的實現。By default there will be an implementation that uses the user's IPrincipal.Identity.Name as the user name.

在集線器中,您可以透過新的 API 向這些使用者傳送訊息:In hubs, you'll be able to send messages to these users via a new API:

使用用戶端.使用者 APIUsing the Clients.User API

public class MyHub : Hub
{
    public void Send(string userId, string message)
    {
        Clients.User(userId).send(message);
    }
}

更好的錯誤處理支援Better Error Handling Support

用戶現在可以從任何中心調用中引發HubException。Users can now throw HubException from any hub invocation. HubException的建構函數可以獲取字串訊息和物件額外的錯誤資料。The constructor of the HubException can take a string message and an object extra error data. SignalR 將自動序列化異常並將其發送到用戶端,其中它將用於拒絕/拒絕中心方法調用。SignalR will auto-serialize the exception and send it to the client where it will be used to reject/fail the hub method invocation.

顯示詳細的集線器異常設置與HubException被發送回客戶端無關;它總是發送。The show detailed hub exceptions setting has no bearing on HubException being sent back to the client or not; it is always sent.

顯示傳送到客戶端傳送 Hubexception 的伺服器端碼Server-side code demonstrating sending a HubException to the client

public class MyHub : Hub
{
    public void Send(string message)
    {
        if(message.Contains("<script>"))
        {
            throw new HubException("This message will flow to the client", new { user = Context.User.Identity.Name, message = message });
        }

        Clients.All.send(message);
    }
}

顯示回應從伺服器傳送的 HubException 的 JavaScript 客戶端碼JavaScript client code demonstrating responding to a HubException sent from the server

myHub.server.send("<script>")
            .fail(function (e) {
                if (e.source === 'HubException') {
                    console.log(e.message + ' : ' + e.data.user);
                }
            });

.NET 用戶端代碼,用於回應從伺服器傳送的 HubException.NET client code demonstrating responding to a HubException sent from the server

try
{
    await myHub.Invoke("Send", "<script>");
}
catch(HubException ex)
{
    Conosle.WriteLine(ex.Message);
}

更簡便的集線器單元測試Easier unit testing of hubs

SignalR 2.0IHubCallerConnectionContext包括一 個在集線器上調用的介面,該介面使創建類比用戶端調用變得更加容易。SignalR 2.0 includes an interface called IHubCallerConnectionContext on Hubs that makes it easier to create mock client side invocations. 以下程式碼段展示使用此介面與流行的測試工具xUnit.netmoqThe following code snippets demonstrate using this interface with popular test harnesses xUnit.net and moq.

帶xUnit.net的單元測試訊號RUnit testing SignalR with xUnit.net

[Fact]
public void HubsAreMockableViaDynamic()
{
    bool sendCalled = false;
    var hub = new MyHub();
    var mockClients = new Mock<IHubCallerConnectionContext>();
    hub.Clients = mockClients.Object;
    dynamic all = new ExpandoObject();
    all.send = new Action<string>(message =>
    {
        sendCalled = true;
    });
    mockClients.Setup(m => m.All).Returns((ExpandoObject)all);
    hub.Send("foo");
    Assert.True(sendCalled);
}

使用 moq 進行單元測試訊號RUnit testing SignalR with moq

[Fact]
public interface IClientContract
{
    void send(string message);
}
public void HubsAreMockableViaType()
{
    var hub = new MyHub();
    var mockClients = new Mock<IHubCallerConnectionContext>();
    var all = new Mock<IClientContract>();
    hub.Clients = mockClients.Object;
    all.Setup(m => m.send(It.IsAny<string>())).Verifiable();
    mockClients.Setup(m => m.All).Returns(all.Object);
    hub.Send("foo");
    all.VerifyAll();

JavaScript 錯誤處理JavaScript error handling

在 SignalR 2.0 中,所有 JavaScript 錯誤處理回調返回 JavaScript 錯誤物件,而不是原始字串。In SignalR 2.0, all JavaScript error handling callbacks return JavaScript error objects instead of raw strings. 這允許 SignalR 將更豐富的資訊流向錯誤處理程式。This allows SignalR to flow richer information to your error handlers. 可以從錯誤的source屬性中獲取內部異常。You can get the inner exception from the source property of the error.

處理 Start.Fail 異常的 JavaScript 客戶端碼JavaScript client code that handles the Start.Fail exception

connection.start().fail(function(e) {
    console.log('The error is: ' + e.message);
});

ASP.NET IdentityASP.NET Identity

新的ASP.NET會員制New ASP.NET Membership System

ASP.NET身份是ASP.NET應用程式的新成員資格系統。ASP.NET Identity is the new membership system for ASP.NET applications. ASP.NET識別使用戶特定的配置檔數據與應用程序資料整合變得容易。ASP.NET Identity makes it easy to integrate user-specific profile data with application data. ASP.NET識別還允許您為應用程式中的使用者配置檔選擇持久性模型。ASP.NET Identity also allows you to choose the persistence model for user profiles in your application. 您可以將資料儲存在 SQL Server 資料庫或其他資料存放區中,包括 NoSQL 資料存放區 (例如 Azure 儲存體資料表)。You can store the data in a SQL Server database or another data store, including NoSQL data stores such as Azure Storage Tables. 有關詳細資訊,請參閱可視化工作室 2013 中創建ASP.NET Web 專案的單個使用者帳戶For more information, see Individual User Accounts in Creating ASP.NET Web Projects in Visual Studio 2013.

宣告架構驗證Claims-based authentication

ASP.NET現在支援基於聲明的身份驗證,其中使用者的身份表示為來自受信任頒發者的一組聲明。ASP.NET now supports claims-based authentication, where the user's identity is represented as a set of claims from a trusted issuer. 使用者可以使用應用程式資料庫中維護的使用者名稱和密碼進行身份驗證,或使用社交身份提供者(例如:微軟帳戶、Facebook、Google、Twitter),或者透過 Azure 活動目錄或活動目錄聯合服務 (ADFS) 使用組織帳戶。Users can be authenticated using a username and password maintained in an application database, or using social identity providers (for example: Microsoft Accounts, Facebook, Google, Twitter), or using organizational accounts through Azure Active Directory or Active Directory Federation Services (ADFS).

與 Azure 的目錄與 Windows 伺服器活動目錄整合Integration with Azure Active Directory and Windows Server Active Directory

現在,您可以創建ASP.NET使用Azure活動目錄或Windows伺服器活動目錄 (AD) 進行身份驗證的專案。You can now create ASP.NET projects that use Azure Active Directory or Windows Server Active Directory (AD) for authentication. 有關詳細資訊,請參閱在Visual Studio 2013 中建立 ASP.NET Web 專案的組織帳戶For more information, see Organizational Accounts in Creating ASP.NET Web Projects in Visual Studio 2013.

OWIN 整合OWIN Integration

ASP.NET身份驗證現在基於OWIN中間件,可用於任何基於OWIN的主機。ASP.NET authentication is now based on OWIN middleware that can be used on any OWIN-based host. 有關 OWIN 的詳細資訊,請參閱以下Microsoft OWIN 元件部分。For more information about OWIN, see the following Microsoft OWIN Components section.

Microsoft OWIN 元件Microsoft OWIN Components

.NET (OWIN) 的開放 Web 介面定義 .NET Web 伺服器和 Web 應用程式之間的抽象。Open Web Interface for .NET (OWIN) defines an abstraction between .NET web servers and web applications. OWIN 將 Web 應用程式與伺服器分離,使 Web 應用程式與主機無關。OWIN decouples the web application from the server, making web applications host-agnostic. 例如,您可以在 IIS 中託管基於 OWIN 的 Web 應用程式,也可以在自訂進程中自承載它。For example, you can host an OWIN-based web application in IIS or self-host it in a custom process.

Microsoft OWIN 元件(也稱為 Katana 專案)中引入的更改包括新的伺服器和主機組件、新的幫助器庫和中間件以及新的身份驗證中間件。Changes introduced in the Microsoft OWIN components (also known as the Katana project) include new server and host components, new helper libraries and middleware, and new authentication middleware.

有關 OWIN 和卡塔納的更多資訊,請參閱OWIN 和卡塔納中的新增功能For more information about OWIN and Katana, see What's new in OWIN and Katana.

注意:OWIN應用程式無法在 IIS 經典模式下運行;它們必須在集成模式下運行。Note: OWIN applications cannot run in IIS classic mode; they must be run in integrated mode.

注意:OWIN應用程式必須完全信任地運行。Note: OWIN applications must be run in full trust.

新伺服器和主機New Servers and Hosts

使用此版本,添加了新的元件以啟用自承載方案。With this release, new components were added to enable self-host scenarios. 這些元件包括以下 NuGet 套件:These components include the following NuGet packages:

  • 微軟.Owin.Host.HTTPListener.Microsoft.Owin.Host.HttpListener. 提供一個 OWIN 伺服器,該伺服器使用HttpListener偵聽 HTTP 請求並將其定向到 OWIN 管道中。Provides an OWIN server that uses HttpListener to listen for HTTP requests and direct them into the OWIN pipeline.
  • Microsoft.Owin.Hosting為希望在自定義進程中自承載 OWIN 管道(如控制台應用程式或 Windows 服務)的開發人員提供一個庫。Microsoft.Owin.Hosting Provides a library for developers who wish to self-host an OWIN pipeline in a custom process, such as a console application or Windows service.
  • 奧溫霍斯OwinHost. 提供一個獨立的可執行檔,用於包裝Microsoft.Owin.Hosting並允許您自承載 OWIN 管道,而無需編寫自定義主機應用程式。Provides a stand-alone executable that wraps Microsoft.Owin.Hosting and lets you self-host an OWIN pipeline without having to write a custom host application.

此外,Microsoft.Owin.Host.SystemWeb該包現在使中間件能夠向SystemWeb伺服器提供提示,指示應在特定的 ASP.NET 管道階段調用中間件。In addition, the Microsoft.Owin.Host.SystemWeb package now enables middleware to provide hints to the SystemWeb server, indicating that the middleware should be called during a specific ASP.NET pipeline stage. 此功能對於身份驗證中間件特別有用,該中間件應在ASP.NET管道中早期運行。This feature is particularly useful for authentication middleware, which should run early in the ASP.NET pipeline.

說明庫和中間件Helper Libraries and Middleware

儘管只能使用 OWIN 規範中的函數和類型定義編寫 OWIN 元件Microsoft.Owin,但新 包提供了一組更使用者友好的抽象。Although you can write OWIN components using only the function and type definitions from the OWIN specification, the new Microsoft.Owin package provides a more user-friendly set of abstractions. 此包將幾個較早的包(例如 ,)Owin.Extensions``Owin.Types合併到單個結構良好的物件模型中,然後其他 OWIN 元件可以輕鬆地使用該模型。This package combines several earlier packages (e.g., Owin.Extensions, Owin.Types) into a single, well-structured object model that can then be easily used by other OWIN components. 事實上,大多數 Microsoft OWIN 元件現在都使用此包。In fact, the majority of Microsoft OWIN components now use this package.

Note

OWIN應用程式無法在IIS經典模式下運行;它們必須在集成模式下運行。OWIN applications cannot run in IIS classic mode; they must be run in integrated mode.

Note

OWIN應用程式必須完全信任地運行。OWIN applications must be run in full trust.

此版本還包括 Microsoft.Owin.診斷包,其中包括用於驗證正在運行的 OWIN 應用程式的中間件,以及幫助調查故障的錯誤頁中間件。This release also includes the Microsoft.Owin.Diagnostics package, which includes middleware to validate a running OWIN application, plus error-page middleware to help investigate failures.

驗證元件Authentication Components

以下身份驗證元件可用。The following authentication components are available.

  • 微軟.Owin.安全.主動目錄.Microsoft.Owin.Security.ActiveDirectory. 使用內部部署或基於雲端的目錄服務啟用身份驗證。Enables authentication using on-premise or cloud-based directory services.
  • 微軟.Owin.Security.cookies支援使用Cookie進行身份驗證。Microsoft.Owin.Security.Cookies Enables authentication using cookies. 此套件以前命名為Microsoft.Owin.Security.FormsThis package was previously named Microsoft.Owin.Security.Forms.
  • 微軟.Owin.Security.Facebook使用Facebook基於OAuth的服務啟用身份驗證。Microsoft.Owin.Security.Facebook Enables authentication using Facebook's OAuth-based service.
  • 微軟.Owin.Security.谷歌使用谷歌基於OpenID的服務啟用身份驗證。Microsoft.Owin.Security.Google Enables authentication using Google's OpenID-based service.
  • 微軟.Owin.Security.Jwt啟用使用 JWT 令牌的身份驗證。Microsoft.Owin.Security.Jwt Enables authentication using JWT tokens.
  • 微軟.Owin.Security.微軟帳戶啟用使用微軟帳戶進行身份驗證。Microsoft.Owin.Security.MicrosoftAccount Enables authentication using Microsoft accounts.
  • 微軟.奧溫.安全.奧烏斯.Microsoft.Owin.Security.OAuth. 提供 OAuth 授權伺服器以及用於驗證無記名權杖的中間件。Provides an OAuth authorization server as well as middleware for authenticating bearer tokens.
  • 微軟.Owin.Security.Twitter使用Twitter基於OAuth的服務進行身份驗證。Microsoft.Owin.Security.Twitter Enables authentication using Twitter's OAuth-based service.

此版本還包括包Microsoft.Owin.Cors,其中包含用於處理跨源 HTTP 請求的中間件。This release also includes the Microsoft.Owin.Cors package, which contains middleware for processing cross-origin HTTP requests.

Note

在 Visual Studio 2013 的最終版本中刪除了對 JWT 簽名的支援。Support for JWT signing has been removed in the final version of Visual Studio 2013.

Entity Framework 6Entity Framework 6

有關實體框架 6 中的新功能和其他更改的清單,請參閱實體框架版本歷史記錄For a list of new features and other changes in Entity Framework 6, see Entity Framework Version History.

ASP.NET剃刀 3ASP.NET Razor 3

ASP.NET Razor 3 包括以下新功能:ASP.NET Razor 3 includes the following new features:

  • 支援選項卡編輯。Support for Tab editing. 以前,使用「保留選項卡」選項時,Visual Studio 中的 「格式文檔」指令、自動縮進和自動格式設定無法正常工作。Previously, the Format Document command, auto indenting, and auto formatting in Visual Studio did not work correctly when using the Keep Tabs option. 此更改糾正了用於選項卡格式的 Razor 代碼的可視化工作室格式。This change corrects Visual Studio formatting for Razor code for tab formatting.
  • 生成連結時支援 URL 重寫規則。Support for URL Rewrite rules when generating links.
  • 刪除安全透明屬性。Removal of security transparent attribute.

    Note

    這是一個重大更改,使 Razor 3 與 MVC4 和更早版本不相容,而 Razor 2 與 MVC5 或針對 MVC5 編譯的程式集不相容。This is a breaking change, and makes Razor 3 incompatible with MVC4 and earlier, while Razor 2 is incompatible with MVC5 or assemblies compiled against MVC5.

Razor 3 問題修復在 Visual Studio 2013 從預發行版本可以在這裡找到.Razor 3 issues fixed in Visual Studio 2013 from pre-release versions can be found here.

ASP.NET應用程式掛起ASP.NET App Suspend

ASP.NET應用程式掛起是 .NET Framework 4.5.1 中的一項改變遊戲規則的功能,它從根本上改變了在一台電腦上託管大量ASP.NET網站的使用者體驗和經濟模型。ASP.NET App Suspend is a game-changing feature in the .NET Framework 4.5.1 that radically changes the user experience and economic model for hosting large numbers of ASP.NET sites on a single machine. 有關詳細資訊,請參閱ASP.NET 應用程式掛起 – 回應式共用 .NET Web 託管For more information, see ASP.NET App Suspend – responsive shared .NET web hosting.

已知問題和重大變更Known Issues and Breaking Changes

本節介紹視覺工作室 2013 ASP.NET和 Web 工具中的已知問題和重大更改。This section describes known issues and breaking changes in the ASP.NET and Web Tools for Visual Studio 2013.

NuGetNuGet

ASP.NET Web APIASP.NET Web API

  1. ODataQueryOptions<T>.ApplyTo(IQueryable)不會總是返回IQueryable<T>,因為我們添加了$select``$expand對和的支援。ODataQueryOptions<T>.ApplyTo(IQueryable) doesn't return IQueryable<T> always, as we added support for $select and $expand.

    我們以前的樣本ODataQueryOptions<T>總是將傳回值ApplyToIQueryable<T>轉換為 。Our earlier samples for ODataQueryOptions<T> always casted the return value from ApplyTo to IQueryable<T>. 這在早期$filter起作用,因為我們支援之前的查詢選項 (、、、、)$orderby``$skip``$top不會更改查詢的形狀。This worked earlier because the query options that we supported earlier ($filter, $orderby, $skip, $top) do not change the shape of the query. $select現在,我們支援$expand,並ApplyTo從返回值IQueryable<T>將 並不總是。Now that we support $select and $expand the return value from ApplyTo will not be IQueryable<T> always.

    // Sample ODataQueryOptions<T> usage from earlier
    public IQueryable<Customer> Get(ODataQueryOptions<Customer> query)
    {
        IQueryable<customer> result="query.ApplyTo(_customers)" as iqueryable<customer>; return result;
    }
    

    如果使用之前的範例代碼,則如果用戶端未發送$select$expand,它將繼續工作。If you are using the sample code from earlier, it will continue working if the client does not send $select and $expand. 但是,如果您希望支援$select,$expand並且必須將該代碼更改為此代碼。However, if you wish to support $select and $expand you have to change that code to this.

    public IHttpActionResult Get(ODataQueryOptions<Customer> query)
    {
        IQueryable result = query.ApplyTo(_customers);
        return Ok(result, result.GetType());
    }
     
    private IHttpActionResult Ok(object content, Type type)
    {
        Type resultType = typeof(OkNegotiatedContentResult<>).MakeGenericType(type);
        return Activator.CreateInstance(resultType, content, this) as IHttpActionResult;
    }
    
  2. 要求.網址或要求上下文.網址在批次處理請求期間為空Request.Url or RequestContext.Url is null during a batch request

    在批次處理方案中 ,UrlHelper請求.Url請求上下文.網址存取時為空。In a batching scenario, UrlHelper is null when accessed from Request.Url or RequestContext.Url.

    此問題目前在此處追蹤:BatchRequestContext.網址 對於批次處理請求為空This issue is currently tracked here: BatchRequestContext.Url is null for batching request.

    此問題的解決方法是建立UrlHelper的新實體,如以下範例所示:The workaround for this issue is to create a new instance of UrlHelper, as in the following example:

    建立 UrlHelper 的新實體Creating a new instance of UrlHelper

    if (RequestContext.Url == null)
    {
        RequestContext.Url = new UrlHelper(Request);
    }
    

ASP.NET MVCASP.NET MVC

  1. 使用 MVC5 與 OrgAuth 時,如果您有執行 AntiForgerToken 驗證的檢視,則當您將資料發布到檢視時,可能會遇到以下錯誤:When using MVC5 and OrgAuth, if you have views which do AntiForgerToken validation, you might come across the following error when you post data to the view:

    錯誤Error:

    '/' 應用程式中有伺服器錯誤。Server Error in '/' Application.

    所提供的索賠身份上不存在http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier類型"https://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider或""的索賠。要使用基於聲明的身份驗證啟用反偽造權杖支援,請驗證已配置的聲明提供者是否在它生成的聲明標識實例上同時提供這兩種聲明。如果配置的聲明提供者使用不同的聲明類型作為唯一識別碼,則可以透過設定靜態屬性 AntiForgeryConfig.唯一ClaimType標識符來配置它。A claim of type 'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier' or 'https://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider' was not present on the provided ClaimsIdentity. To enable anti-forgery token support with claims-based authentication, please verify that the configured claims provider is providing both of these claims on the ClaimsIdentity instances it generates. If the configured claims provider instead uses a different claim type as a unique identifier, it can be configured by setting the static property AntiForgeryConfig.UniqueClaimTypeIdentifier.

    因應措施Workaround:

    在 Global.asax 中新增以下行以修復它:Add the following line in Global.asax to fix it:

    AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.Name;

    這將在下一個版本中修復。This will be fixed for the next release.

  2. 將 MVC4 應用升級到 MVC5 後,生成解決方案並啟動它。After upgrading an MVC4 app to MVC5, build the solution and launch it. 您應該會看到以下錯誤:You should see the following error:

    [A]系統.Web.WebPages.Razor.配置.Host節不能強制轉換為 [B_system.Web.Web.WebPages.Razor.配置.主機節。[A]System.Web.WebPages.Razor.Configuration.HostSection cannot be cast to [B]System.Web.WebPages.Razor.Configuration.HostSection. 類型 A 源自 "系統.Web.WebPages.Razor" 版本=2.0.0.0,區域性=中性,PublicKeyToken=31bf3856ad364e35"在上下文_"預設"的位置 "C:_windows.Net_大會_GAC MSIL_System.WebPages.Razor_v4.0.0___31bf3856ad36e35_系統.WebPages.剃鬚刀.剃鬚刀。"Type A originates from 'System.Web.WebPages.Razor, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' in the context 'Default' at location 'C:\windows\Microsoft.Net\assembly\GAC_MSIL\System.Web.WebPages.Razor\v4.0_2.0.0.0__31bf3856ad364e35\System.Web.WebPages.Razor.dll'. 類型 B 源自 'System.Web.WebPages.Razor, 版本=3.0.0.0, 區域性= 中性, PublicKeyToken_31bf3856ad364e35"在上下文"預設"的位置"C:_Windows_Microsoft.NET_Framework_v4.0.30319\臨時ASP.NET檔\root_6d 05bbd0_e8b5908e_assembly_dl3_c9cbca63_f8910382_6273ce01_System.WebPages.Razor.dll'。Type B originates from 'System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' in the context 'Default' at location 'C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\root\6d05bbd0\e8b5908e\assembly\dl3\c9cbca63\f8910382_6273ce01\System.Web.WebPages.Razor.dll'.

    要修復上述錯誤,請開啟項目中的所有Web.config 檔(包括"檢視'資料夾中的檔案),並執行以下操作:To fix the above error, open all the Web.config files (including the ones in the Views folder) in your project and do the following:

    1. 將"System.Web.Mvc"版本"4.0.0.0"的所有匹配項更新為"5.0.0.0"。Update all occurrences of version "4.0.0.0" of "System.Web.Mvc" to "5.0.0.0".

    2. 更新"系統.Web.Helpers"、系統.Web.WebPages"和"系統.Web.WebPages.Razor"到"3.0.0.0"版本的所有匹配項Update all occurrences of version "2.0.0.0" of "System.Web.Helpers", "System.Web.WebPages" and "System.Web.WebPages.Razor" to "3.0.0.0"

      例如,在進行上述更改後,程式集綁定應如下所示:For example, after you make the above changes, the assembly bindings should look like this:

      <dependentAssembly>
        <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="3.0.0.0" />
        </dependentAssembly>
        <dependentAssembly>
        <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="3.0.0.0" />
        </dependentAssembly>
        <dependentAssembly>
        <assemblyIdentity name="System.Web.WebPages.Razor" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
        </dependentAssembly>
        <dependentAssembly>
        <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-4.0.0.0" newVersion="5.0.0.0" />
      </dependentAssembly>
      

      有關將 MVC 4 專案升級到 MVC 5 的資訊,請參閱如何將 ASP.NET MVC 4 和 Web API 專案升級到 ASP.NET MVC 5 和 Web API 2For information on upgrading MVC 4 projects to MVC 5, see How to Upgrade an ASP.NET MVC 4 and Web API Project to ASP.NET MVC 5 and Web API 2.

  3. 當將客戶端驗證與 jQuery 不顯眼驗證一起使用時,對於類型="數位"的 HTML 輸入元素,驗證消息有時不正確。When using client-side validation with jQuery Unobtrusive Validation, the validation message is sometimes incorrect for an HTML input element with type='number'. 輸入無效號碼時將顯示所需值的驗證錯誤("需要"年齡欄位),而不是需要有效編號的正確消息。The validation error for a required value ("The Age field is required") is shown when an invalid number is entered instead of the correct message that a valid number is required.

    在"創建"和"編輯"檢視中具有整數屬性的模型的腳手架代碼通常會產生此問題。This issue is commonly found with scaffolded code for a model with an integer property on the Create and Edit views.

    要解決此問題,從以下方面更改編輯器説明程式:To work around this issue, change the editor helper from:

    @Html.EditorFor(person => person.Age)

    變更為:To:

    @Html.TextBoxFor(person => person.Age)

  4. ASP.NET MVC 5 不再支援部分信任。ASP.NET MVC 5 no longer supports partial trust. 連結到 MVC 或 WebAPI 二進位檔案的專案應刪除安全透明屬性和「允許部分受信任的呼叫者」屬性。Projects linking to the MVC or WebAPI binaries should remove the SecurityTransparent attribute and the AllowPartiallyTrustedCallers attribute. 刪除這些屬性將消除編譯器錯誤,如下所示。Removing these attributes will eliminate compiler errors such as the following.

    Attempt by security transparent method ‘MyComponent' to access security critical type 'System.Web.Mvc.MvcHtmlString' failed. Assembly 'PagedList.Mvc, Version=4.3.0.0, Culture=neutral, PublicKeyToken=abbb863e9397c5e1' is marked with the AllowPartiallyTrustedCallersAttribute, and uses the level 2 security transparency model. Level 2 transparency causes all methods in AllowPartiallyTrustedCallers assemblies to become security transparent by default, which may be the cause of this exception.

    請注意,作為副作用,您不能在同一應用程式中使用 4.0 和 5.0 程式集。Note, as a side effect of this you cannot use 4.0 and 5.0 assemblies in the same application. 您需要將所有它們更新為 5.0。You need to update all of them to 5.0.

具有 Facebook 授權的 SPA 樣本可能會導致 IE 不穩定,而網站託管在 Intranet 區域中SPA Template with Facebook authorization may cause instability in IE while the web site is hosted in intranet zone

SPA 模板提供帶 Facebook 的外部登錄。The SPA template provides external log in with Facebook. 當使用範本創建的專案在本地運行時,登錄可能會導致 IE 崩潰。When the project created with the template is running locally, signing in may cause IE to crash.

解決方案:Solution:

  1. 在互聯網區域託管網站;或Host the web site in internet zone; or

  2. 在 IE 以外的瀏覽器中測試方案。Test the scenario in a browser other than IE.

Web Forms ScaffoldingWeb Forms Scaffolding

Web 窗體基架已從 VS2013 中刪除,將來將更新為 Visual Studio。Web Forms Scaffolding has been removed from VS2013 and will be available in a future update to Visual Studio. 但是,您仍可以通過添加 MVC 依賴項和生成 MVC 基架來在 Web 窗體專案中使用基架。However, you can still use scaffolding within a Web Forms project by adding MVC dependencies and generating scaffolding for MVC. 您的專案將包含 Web 窗體和 MVC 的組合。Your project will contain a combination of Web Forms and MVC.

要將 MVC 新增到 Web 窗體專案,請新增新的文手架項目,然後選擇MVC 5 相依項 。To add MVC to your Web Forms project, add a new scaffolded item and select MVC 5 Dependencies. 根據是否需要所有內容檔(如腳本)選擇"最小"或"完整"Select either Minimal or Full depending on whether you need all of the content files, such as scripts. 然後,為 MVC 添加一個基架項,這將在專案中創建檢視和控制器。Then, add a scaffolded item for MVC, which will create views and a controller in your project.

MVC 與 Web API 基架 - HTTP 404,找不到錯誤MVC and Web API Scaffolding - HTTP 404, Not Found error

如果在向專案添加基架項時遇到錯誤,則專案可能會處於不一致狀態。If an error is encountered when adding a scaffolded item to a project, it is possible your project will be left in an inconsistent state. 對基架所做的一些更改將回滾,但其他更改(如已安裝的 NuGet 包)將不會回滾。Some of the changes made be scaffolding will be rolled back but other changes, such as the installed NuGet packages, will not be rolled back. 如果路由配置更改回滾,則使用者在導航到基架專案時將收到 HTTP 404 錯誤。If the routing configuration changes are rolled back, users will receive an HTTP 404 error when navigating to scaffolded items.

因應措施:Workaround:

  • 要修復 MVC 的此錯誤,請添加新的腳手架項並選擇 MVC 5 依賴項(最小或完整)。To fix this error for MVC, add a new scaffolded item and select MVC 5 Dependencies (either Minimal or Full). 此過程將添加專案所需的所有更改。This process will add all of the required changes to your project.

  • 要修復 Web API 的此錯誤,本文:To fix this error for Web API:

    1. 將 WebApiConfig 類添加到專案中。Add the WebApiConfig class to your project.

      public static class WebApiConfig
      {
          public static void Register(HttpConfiguration config)
          {
              config.MapHttpAttributeRoutes();
              config.Routes.MapHttpRoute(
                  name: "DefaultApi",
                  routeTemplate: "api/{controller}/{id}",
                  defaults: new { id = RouteParameter.Optional }
              );
          }
      }
      
      Public Module WebApiConfig
          Public Sub Register(ByVal config As HttpConfiguration)
              config.MapHttpAttributeRoutes()
              config.Routes.MapHttpRoute(
                name:="DefaultApi",
                routeTemplate:="api/{controller}/{id}",
                defaults:=New With {.id = RouteParameter.Optional}
              )
          End Sub
      End Module
      
    2. 在 Global.asax_中的應用程式 啟動方法中設定 WebApiConfig.註冊,如下所示:Configure WebApiConfig.Register in the Application_Start method in Global.asax as follows:

      public class WebApiApplication : System.Web.HttpApplication
      {
          protected void Application_Start()
          {
              GlobalConfiguration.Configure(WebApiConfig.Register);    
          }
      }
      
      Public Class WebApiApplication
           Inherits System.Web.HttpApplication
       
           Sub Application_Start()     
             GlobalConfiguration.Configure(AddressOf WebApiConfig.Register)       
           End Sub
      End Class