码迷,mamicode.com
首页 > Web开发 > 详细

[转载]Getting Started with ASP.NET vNext and Visual Studio 14

时间:2014-08-01 15:46:11      阅读:396      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   http   os   strong   io   for   

说在转载之前的话:
ASP.NET框架之前不断做大,而vNext则是从头开始,对ASP.NET框架进行拆分并瘦身,面对不同的需求而更加灵活,各个拆分出来的模块更加轻量。
vNext的出现,对ASP.NET开发人员又是一次洗礼,ASP.NET开发人员是辛苦的,但也幸运的;俗话说,不进则退,vNext - 新的学习方向。

--------------------------------------------------------------------------------------------------------

www.asp.net/vnext/overview/aspnet-vnext/getting-started-with-aspnet-vnext-and-visual-studio

 

The next version of ASP.NET (“ASP.NET vNext”) has been redesigned from the ground up. The goal is to create a lean and composable .NET stack for building modern cloud-based apps.

You don‘t have to use Visual Studio to develop ASP.NET vNext applications. You can develop and run vNext on platforms that Visual Studio doesn‘t run on. But Visual Studio provides the best development experience, and this tutorial introduces you to that experience.

Note: This tutorial has been updated for CTP2.

Introduction to ASP.NET vNext

Here are some of the new features in ASP.NET vNext.

Rebuilt from the Ground Up

  • MVC, Web API, and Web Pages are merged into one framework, called MVC 6. The new framework uses a common set of abstractions for routing, action selection, filters, model binding, and so on.
  • Dependency injection is built into the framework. Use your preferred IoC container to register dependencies.
  • vNext is host agnostic. You can host your app in IIS, or self-host in a custom process. (Web API 2 and SignalR 2 already support self-hosting; vNext brings this same capability to MVC.)
  • vNext is open source and cross platform.

Leaner, Faster

  • MVC 6 has no dependency on System.Web.dll. The result is a leaner framework, with faster startup time and lower memory consumption.
  • vNext apps can use a cloud-optimized runtime and subset of the .NET Framework. This subset of the framework is about 11 megabytes in size compared to 200 megabytes for the full framework, and is composed of a collection of NuGet packages.
  • Because the cloud-optimized framework is a collection of NuGet packages, your app can include only the packages you actually need. No unnecessary memory, disk space, loading time, etc.
  • Microsoft can deliver updates to the framework on a faster cadence, because each part can be updated independently.

True Side-by-Side Deployment

The reduced footprint of the cloud-optimized runtime makes it practical to deploy the framework with your app.

  • You can run apps side-by-side with different versions of the framework on the same server.
  • Your apps are insulated from framework changes on the server.
  • You can make framework updates for each app on its own schedule.
  • No errors when you deploy to production resulting from a mismatch between the framework patch level on the development machine and the production server.

New Development Experience

vNext uses the Roslyn compiler to compile code dynamically.

  • You can edit a code file, refresh the browser, and see the changes without rebuilding the project.
  • Besides streamlining the development process, dynamic code compilation enables development scenarios that were not possible before, such as editing code on the server using Visual Studio Online ("Monaco").
  • You can choose your own editors and tools.

ASP.NET vNext is being rewritten from the ground up, and while much of your code for vNext will look the same, vNext is not backwards compatible with existing ASP.NET applications. However, the current frameworks (Web Forms 5, MVC 5, Web API 2, Web Pages 3, SignalR 2, and Entity Framework 6) will continue to ship in Visual Studio, and will be fully supported in ASP.NET vNext.

Sections of this tutorial

Intended audience

This tutorial assumes that you have worked with ASP.NET web projects in Visual Studio. It focuses on what‘s new in vNext and the new features in Visual Studio "14" CTP for working with vNext projects.

If you have worked with ASP.NET Web Forms or Web Pages but not MVC, it would be helpful to go through an Introduction to MVC first.

Prerequisites

This tutorial requires Visual Studio "14" CTP.

It is recommended to install the Visual Studio "14" CTP on a VM, VHD, or fresh computer. There are known side-by-side compatibility issues with Visual Studio 2013. Learn more about what’s in the Visual Studio “14” CTP.

For the optional section that deploys your vNext application to Azure, you‘ll need an Azure subscription to work with. If you don‘t already have an Azure account, but you do have an MSDN subscription, you can activate your MSDN subscription benefits. Otherwise, you can create a free trial account in just a couple of minutes. For details, see Windows Azure Free Trial.

Create an empty vNext project

You‘ll start by creating a vNext web project with the minimum required files and will take a look at those files. Then you‘ll add an MVC controller and view, and later you‘ll see how to add and reference a class library. 

  1. Start Visual Studio "14" CTP.

  2. On the Start Page, click New Project, and then in the New Project dialog, select the C# / Web templates.

  3. Select the ASP.NET vNext Empty Web Application template, name the project HelloWorld, and click OK.

    bubuko.com,布布扣

    In Solution Explorer you can see the two files that are required for a vNext web application: project.json and Startup.cs.

    bubuko.com,布布扣

project.json

The project.json file contains a list of dependencies for the project and a list of build output configurations. It can also include a list of commands.

Dependencies

Dependencies are NuGet packages or other projects. For the empty vNext web project the only dependency is the Microsoft.AspNet.Server.IIS NuGet package, which enables the application to run in IIS.

{
    "dependencies": {
        "Microsoft.AspNet.Server.IIS" : "1.0.0-alpha2"
    }
}

(Depending on when you do the tutorial, you might see a different version number.)

For NuGet package dependencies, Visual Studio asynchronously restores any missing packages when the project loads. You may have noticed that the HelloWorld project loaded instantly, but look at the Output window and you‘ll see that it took several seconds to restore Microsoft.AspNet.Server.IIS and a dozen or so packages that it depends on.

bubuko.com,布布扣

Build output configurations

The project.json file also specifies build output configuration options.

{
    "configurations": {
        "net45": { },
        "k10": { }
    }
}

These settings correspond to the Active Target Framework options in the Property Pages window in Visual Studio. To view this window, right-click the project in Solution Explorer and select Properties.

bubuko.com,布布扣

With the Active Target Framework still set to .NET 4.5.1, look at the References node in Solution Explorer.

 bubuko.com,布布扣

Microsoft.AspNet.Server.IIS and other framework NuGet packages appear under the .NET Framework 4.5 node. If you expand the Microsoft.AspNet.Server.IIS node, you‘ll see that it combines dll references and NuGet package references and treats them as one unit. This hides dependencies and makes the references list more manageable.

Go back to the project properties page, change the Active Target Framework to .NET Core Framework 4.5, and then look at Solution Explorer again.

Visual Studio has changed the project references to reflect the fact that your project is now running under the cloud-optimized subset of the framework.

bubuko.com,布布扣

Commands

The project.json file can also contain commands that facilitate running the application from the command line. For example:

{
    "commands": {
        /* Change the port number when you are self hosting this application */
        "web": "Microsoft.AspNet.Hosting --server Microsoft.AspNet.Server.WebListener --server.urls http://localhost:5000"
    }
}

This tutorial does not show how to run vNext applications from the command line. For more information, see the project wiki on GitHub.

Startup.cs

By default, the vNext hosting environment expects to find a startup class named Startup. This class must contain a Configure method that takes an IBuilder parameter, and you configure the HTTP pipeline inside this Configure method. The empty project creates the class with nothing in the Configure method.

using System;
using Microsoft.AspNet.Builder;

namespace HelloWorld
{
    public class Startup
    {
        public void Configure(IBuilder app)
        {
        }
    }
}

You‘ll add code to the Configure method when you add ASP.NET MVC functionality to the project in the next section of the tutorial.

Add a controller and view

To enable MVC in the HTTP pipeline you‘ll add a NuGet package and configure the Startup class.

  1. In project.json, add a comma at the end of the Microsoft.AspNet.Server.IIS line, and then add the MVC package as shown. Type in the changes rather than copying and pasting, and don‘t save your changes yet.

    {
        "dependencies": {
            "Microsoft.AspNet.Server.IIS": "1.0-alpha2",
            "Microsoft.AspNet.Mvc": "6.0-alpha2"
        }
    }

    Notice that you get IntelliSense for adding references.

    bubuko.com,布布扣

    The IntelliSense list is taken from the default NuGet package source and from other projects in folders that are siblings to the project folder. 

    The code in quotes after the colon specifies the version of the package to load.  You can specify the exact version ("6.0-alpha2"), use an empty string to specify the latest available, or use wildcards to specify the latest available of a specified set ("1.0-alpha2-*").

  2. Keep the Output window visible, and then save your changes.

    You‘ll notice that Visual Studio watches for changes in the project.json file and automatically restores packages that are added to it. (Actual version numbers on your computer may be different from this screen shot.)

    bubuko.com,布布扣

    Visual Studio does not delete packages when you delete dependencies from project.json. But the packages folder is typically not included in source control, and the next time the project is retrieved from source control the deleted dependencies won‘t be restored.

  3. To configure the Startup class, add the highlighted using statement and configuration code.

    using System;
    using Microsoft.AspNet.Builder;
    using Microsoft.Framework.DependencyInjection;
    namespace HelloWorld
    {
        public class Startup
        {
            public void Configure(IBuilder app)
            {
                app.UseServices(services =>
                {
                    services.AddMvc();
                });
    
                app.UseMvc();        }
        }
    }

    The AddMvc method adds the MVC framework services to the dependency injection system. The UseMvc method configures MVC default settings such as routes.

  1. Create a Controllers folder, and in the folder create a new file named HomeController.cs, using the MVC Controller Class new item template.

    bubuko.com,布布扣

  2. Create a Views folder.
  3. In the Views folder, create a subfolder named Home.
  4. In the Home folder, add a view named Index.cshtml, using the MVC 5 View Page (Razor) new item template.

    bubuko.com,布布扣

  5. Replace the template code in the Index.cshtml page with the following code.

    The current time is : @System.DateTime.Now.ToString()
  6. Run the project.

    The browser displays the date and time from the Index.cshtml page. By default the application is hosted by IIS Express.

    bubuko.com,布布扣

Create a vNext project with a class library

In this section you‘ll create a new project by using the ASP.NET vNext Web Application template and see what it adds compared to the ASP.NET vNext Empty Web Application template. You‘ll see an example of vNext configuration settings, and then you‘ll add a class library project and set a reference to it in the web project.

  1. From the File menu click New Project, and then in the New Project dialog, select the C# / Web templates.

  2. Select the ASP.NET vNext Web Application template, name the project HelloWorld2, and click OK.

    bubuko.com,布布扣

    In addition to the project.json and the Startup.cs files, which are the same as what you‘ve already seen, this project contains files needed for a simple MVC application, including CSS files, script files, and a Home controller and views.  It also includes an Account controller and views, which enables users to log in, using ASP.NET Identity.

    bubuko.com,布布扣

    Look at the References node in Solution Explorer. Solution Explorer organizes the references so that it‘s not a long list to scroll through. For example, all of the MVC packages appear under the Microsoft.AspNet.Mvc node.

    bubuko.com,布布扣

vNext configuration

The template creates a config.json file to store application settings such as database connection strings:

{
    "Data": {
        "DefaultConnection": { 
            "ConnectionString": "Server=(localdb)\\mssqllocaldb;Database=aspnetvnext-HelloWorld2-f0652fd2-febf-488d-955b-b4c590e536f1;Trusted_Connection=True;MultipleActiveResultSets=true"
        }
    }
}

In a vNext project, you can use a Web.config file for application settings, but you also have other options. For example, you can install NuGet packages with configuration providers for .ini files or .json files. The template uses Microsoft.Framework.ConfigurationModel.Json and creates a config.json. The Startup class includes this code that gets settings from config.json and also from environment variables:

var configuration = new Configuration();
configuration.AddJsonFile("config.json");
configuration.AddEnvironmentVariables();

The Configuration class also provides other methods for working with configuration data, such as a Get method that enables you retrieve a specified setting. The following code would retrieve the value of the connection string shown earlier in config.json.

var configuration = new Configuration();
configuration.AddJsonFile("config.json");
string connString = configuration.Get("Data:DefaultConnection:ConnectionString");

Add a class library project

  1. Add to the solution an ASP.NET vNext Class Library project, leaving the default name ClassLibrary1. (Make sure you don‘t use the class library template under Windows Desktop; you have to use the vNext one under Web.)

    bubuko.com,布布扣 

  2. In the HelloWorld2 web project, open the project.json file and add a line to set a reference to the class library project. Type in the new code instead of copying and pasting it in order to see that IntelliSense gives you ClassLibrary1 as an option you can select.

    {
        "dependencies": {
            "EntityFramework.SqlServer": "7.0.0-alpha2",
            "Microsoft.AspNet.Mvc": "6.0.0-alpha2",
            "Microsoft.AspNet.Identity.EntityFramework": "3.0.0-alpha2",
            "Microsoft.AspNet.Identity.Authentication": "3.0.0-alpha2",
            "Microsoft.AspNet.Security.Cookies": "1.0.0-alpha2",
            "Microsoft.AspNet.Server.IIS": "1.0.0-alpha2",
            "Microsoft.AspNet.Server.WebListener": "1.0.0-alpha2",
            "Microsoft.AspNet.StaticFiles": "1.0.0-alpha2",
            "Microsoft.Framework.ConfigurationModel.Json": "1.0.0-alpha2",
            "Microsoft.VisualStudio.Web.BrowserLink.Loader": "14.0-alpha2",
            "Classlibrary1": ""
        },

    When you save the file, the References node in Solution Explorer shows the class library project and identifies it as a project in the properties window (other references such as Microsoft.AspNet.Server.IIS show up as NuGet package references).

    bubuko.com,布布扣

  3. In the ClassLibrary1 project, open Class1.cs and add the highlighted code to create a method that returns a "hello world" value.

    public class Class1
    {
        public Class1()
        {
    
        }
        public static string GetMessage()
        {
            return "Hello World from ClassLibrary1!";
        }}
  4. In the HelloWorld2 project, open Controllers\HomeController.cs and call the new class library method from the About action method.

    public IActionResult About()
    {
        ViewBag.Message = Classlibrary1.Class1.GetMessage();
    
        return View();
    }
  5. Press CTRL+F5 to run the project (don‘t run in debug mode).

    You see the home page in the browser.

    bubuko.com,布布扣

  6. Go to the About page to see your hello world message.

    bubuko.com,布布扣

  7. With the browser still open, open Class1.cs and change the message text to "New message from ClassLibrary1!".

  8. Save the file. Don‘t rebuild the project.

  9. Refresh the browser.

    You see the result of your changes in the browser. The code file was recompiled without your having to rebuild the project.

    (If the changes don‘t appear in the browser, make sure you ran the project by pressing CTRL+F5, not just F5. Dynamic recompile works by restarting the process. That doesn‘t happen when you‘re debugging because Visual Studio would have to detach from the process.)

    bubuko.com,布布扣

    If you look at the bin folder, you‘ll see there are no project dlls there -- your source code is dynamically compiled to memory.

Deploy to Azure

In this optional section, you deploy the project to the cloud and run it there.

  1. Right-click the HelloWorld2 project and click Publish.

  2. In the Publish Web wizard, click Azure Web Sites.

    bubuko.com,布布扣

  3. Sign in to Azure if you aren‘t already signed in.

  4. Click New to create a new web site in Azure.

    bubuko.com,布布扣

  5. Enter a unique site name, choose a region near you, and then click Create.

    bubuko.com,布布扣

    As an alternative, you could also choose to create a database in order to register and log on users in the cloud using ASP.NET Identity. The process for doing that is the same as in the current ASP.NET release.

  6. On the Connection tab, click Publish.

    bubuko.com,布布扣

    Visual Studio publishes the project to Azure and then opens a browser to the home page.

    bubuko.com,布布扣

Visual Studio project and solution files

ASP.NET vNext is designed to work on many platforms, including those on which Visual Studio doesn‘t run. If you create a project in one of those other environments and want to work on it in Visual Studio, all you have to do is open the project.json file and Visual Studio automatically creates the other files that it needs: a solution file (.sln) and a project file (.kproj).  In this section of the tutorial you‘ll see how this works.

  1. Open your HelloWorld2 solution folder in File Explorer

  2. Close the solution in Visual Studio.

  3. Set File Explorer to show hidden files and file extensions (View tab, select Hidden items and File name extensions).

  4. Delete the .suo and .sln files, and the .sln.ide and packages folders.

  5. In the ClassLibrary1 and HelloWorld2 project folders, delete the .kproj and .kproj.user files and the bin and obj folders.

    Now all you have left is project source code and project.json files. This is all you need to develop, compile, and run a vNext application if you want to do that without using Visual Studio.

  6. In Visual Studio, from the File menu, select Open > Project/Solution. and open the project.json file in the HelloWorld2 project folder.

    Based on the contents of the folders and the dependencies in the project.json file, Visual Studio figures out the entire solution structure and automatically re-creates the solution, as you can see in Solution Explorer.

    bubuko.com,布布扣

  7. Click the Save All Files icon to save the new .sln and .kproj files.

  8. Open the HelloWorld2 solution folder in File Explorer, and you‘ll see that the packages folder has also been restored.

    bubuko.com,布布扣

  9. Open the ClassLibrary1 project folder, and you‘ll see that the .kproj files are back.

    bubuko.com,布布扣

  10. Leave File Explorer opened to the ClassLibrary1 project.

You can also make changes outside of Visual Studio after opening a project in Visual Studio, and those changes are automatically picked up. 

  1. Open the Class1.cs file in a text editor such as Notepad, change both occurrences of "Class1" to "Class2", and then save the file in the same folder as Class2.cs.

  2. Go back to Visual Studio, and you see that the new file is automatically added to the project.

    bubuko.com,布布扣

Build and Run vNext Apps from the Command Line

You can build and run vNext applications from within Visual Studio or from the command-line. The project.json file contains commands that facilitate running the application from the command line. For example:

{
    "commands": {
        /* Change the port number when you are self hosting this application */
        "web": "Microsoft.AspNet.Hosting --server Microsoft.AspNet.Server.WebListener --server.urls http://localhost:5000"
    }
}

In this section, you will use the web command provided by the Visual Studio template to run the application from the command-line and host it in its own process. To set up your environment to run commands you will need to install the K Version Manager (KVM) tool, which is used to retrieve different versions of the runtime and allow you to switch between them. You then run commands using the K script.

  1. Run the following command from a command-line prompt to install the K Version Manager.
    @powershell -NoProfile -ExecutionPolicy unrestricted -Command "iex ((new-object net.webclient).DownloadString(‘https://raw.githubusercontent.com/aspnet/Home/master/kvminstall.ps1‘))"
  2. Run kvm list to see the set of runtimes installed on your machine. Currently none are active for use on the command-line.
  3. Run kvm alias to see the set of available aliases for runtime versions. Aliases make it easier to specify the specific version of the runtime you want to use. Notice that Visual Studio has already set up a default alias.
  4. Run kvm use default to use the version of the runtime specified by that alias. Run kvm list again to see that the desktop (not the cloud-optimized) version of the runtime is now active.
  5. Switch directories to the directory of the project.json file containing the web command for the app.
  6. Run k web to start the application.
  7. Once the console output indicates that the app is started, browse to the address specified in your web command (http://localhost:5000/) to see the running application.

Next Steps

In this tutorial you‘ve seen a quick introduction to developing ASP.NET vNext applications using Visual Studio. For more information about ASP.NET vNext and for vNext sample applications, see the following resources:

Feedback is welcome. You can provide feedback in GitHub, in comments on this page, or in the ASP.NET VNext forum. If you ask a question in StackOverflow, use the asp.net-vnext tag. You can make suggestions for new features on the UserVoice site.

[转载]Getting Started with ASP.NET vNext and Visual Studio 14,布布扣,bubuko.com

[转载]Getting Started with ASP.NET vNext and Visual Studio 14

标签:des   style   blog   http   os   strong   io   for   

原文地址:http://www.cnblogs.com/Benoly/p/3884897.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!