Explicitasp.net
asp.net 时间:2021-04-18 阅读:(
)
ASP.
NET5andMVC6OutlineMotivationDNXASP.
NET5MVC6MotivationModernwebstackUpdatedbuildsystem(nobuildstep)Modernpackagesystem(NuGet)Lightweight/composableruntimeDependencyinjectioneverywhereFlexibleconfiguration/deploymentUnifyMVC/WebAPICrossplatform/portabilitySxSCLRCoreCLROpensourceversionof.
NEThttps://github.
com/dotnet/coreclrContainscoreruntimeandmscorlib(e.
g.
GC,JIT,BCL)Dotnotcontainmanyframeworks(e.
g.
WCF,WPF)CrossplatformWindows,Linux,Mac,FreeBSDPortableDesignedtobe~/bindeployedDNXSDK/toolingtouseaCLRdnvm,dnx,dnu,project.
jsonRuntimehosttoloadaCLRCommandlineorfromotherhost(e.
g.
IIS)ApplicationhostCompileapplicationwithRoslynInvokeapplicationwithdependencyinjection"TheDNX(a.
NETExecutionEnvironment)containsthecoderequiredtobootstrapandrunanapplication,includingthecompilationsystem,SDKtools,andthenativeCLRhosts.
"ComparisontoNode.
jsNodeDNXRuntimeJavaScriptC#/RoslynV8CoreCLRToolingnpmdnu/NuGetNodednxFrameworksConnect*ASP.
NET5Express*MVC6Sequelize*EF7Socket.
io*SignalR3*andtypicallybetween5and20otherchoicesGettingDNX(withoutVisualStudio)WindowsMac@powershell-NoProfile-ExecutionPolicyunrestricted-Command"&{$Branch='dev';iex((new-objectnet.
webclient).
DownloadString('https://raw.
githubusercontent.
com/aspnet/Home/dev/dnvminstall.
ps1'))}"ruby-e"$(curl-fsSLhttps://raw.
githubusercontent.
com/Homebrew/install/master/install)"brewtapaspnet/dnxbrewupdatebrewinstalldnvmDNXcommandlinetoolsDNVM–CLRinstaller/chooserPATHcontains%USERPROFILE%\.
dnx\binContainsdnvm.
cmdanddnvm.
ps1RuntimespecifictoolsDNU–projectutilityDNX–applicationloaderDNVMInstalls/usesaversionoftheCLRCommandslistinstalluse"use"addsaruntimetoPATHDNXHostsanapplicationLoadsCLRCompilesapplicationcodeExecutesMainusingSystem;publicclassProgram{publicvoidMain(){Console.
WriteLine("HelloDNX!
");}}DNXproject.
jsonrequiredConfiguresRuntimesDependenciesCommandsAndmore…{"dependencies":{"Microsoft.
AspNet.
Mvc":"6.
0.
0-beta4"},"frameworks":{"dnx451":{},"dnxcore50":{"dependencies":{"System.
Console":"4.
0.
0-beta-22816"}}},"commands":{"my_command":"YourApp"}}RunningDNXdnxtoapplicationorproject.
jsonisprojectnameorcommandfromproject.
jsondnxruntoapplicationorproject.
json"run"ishardcodedcommandtouse'sprojectnameDNUUtilitytomanage:DependenciesPackagingPublishingOtherutilitiesUsesproject.
jsonProducesproject.
lock.
jsonApplicationdevelopmentdetailsCommandlineargumentsInter-projectdependenciesDependencyinjectionPassingcommandlineargumentsParameterspassedafterarepassedtoapplicationusingSystem;usingSystem.
Linq;publicclassProgram{publicvoidMain(string[]args){Console.
WriteLine(args.
Aggregate((x,y)=>xy));}}Inter-projectdependenciesProjectscanreferenceotherprojectsSource-leveldependency,ratherthanNuGetpackagesDependenciesarelocatedin:Implicitviaproject'sparentdirectoryExplicitviaglobal.
jsonglobal.
jsonresidesinancestordirectory{"projects":["src","test","c:\\other"]}DependencyinjectionDependenciesareinjectedintoProgram'sctorusingSystem;usingMicrosoft.
Framework.
Runtime;publicclassProgram{privatereadonlyIApplicationEnvironment_env;publicProgram(IApplicationEnvironmentenv){_env=env;}publicvoidMain(string[]args){Console.
WriteLine(_env.
ApplicationName);Console.
WriteLine(_env.
ApplicationBasePath);Console.
WriteLine(_env.
RuntimeFramework);}}VisualStudio2015Project.
jsonisprojectfileRunsthecommandlinetoolsAddsbellsandwhistlesIntellisense/quickactionsUIforNuGetUIfortoolingDebuggerOmniSharpRoslynasaserviceIntellisenseStatementcompletionRefactoringPluginsforcommoneditorsSublimeAtomVIMBracketsVSCodeEmacsASP.
NET5NewhostingmodelNewHTTPpipelineASP.
NET5ASP.
NET5isHTTPpipelineimplementationsupportsvariousservers(IIS,WebListener,Kestrel.
.
)canrunOWINand"native"middlewareUsesahigherlevelabstractionoverOWINconcept(HttpContext&RequestDelegate)MVC6isMicrosoft'sapplicationframeworkisOWINcompatibleHostServerOWINMiddlewareASP.
NET5MiddlewareUserAgentMVC6HowASP.
NET5getsinvokeddnx.
commandMicrosoft.
Framework.
ApplicationHostMicrosoft.
AspNet.
Hosting(WebListener,Kestrel,IIS)HeliosIISStartup.
csConfigureServices(…)Configure(…)PipelineprimitivesStartapp.
Use(context,next)app.
Map("/path")app.
Use(context,next)app.
Run(context)app.
Use(context,next)app.
Run(context)IApplicationBuilder.
Run(RequestDelegatehandler)app.
Run(asynccontext=>{awaitcontext.
Response.
WriteAsync("HelloASP.
NET5");});namespaceMicrosoft.
AspNet.
Builder{publicdelegateTaskRequestDelegate(HttpContextcontext);}IApplicationBuilderMap(stringpath,Actionapp)app.
Map("/hello",helloApp=>{helloApp.
Run(async(HttpContextcontext)=>{awaitcontext.
Response.
WriteAsync("HelloASP.
NET5");});});IApplicationBuilderUse(Funcmiddleware)app.
Use(next=>asynccontext=>{if(!
context.
Request.
Path.
Value.
EndsWith("/favicon.
ico")){Console.
WriteLine("pre");Console.
WriteLine(context.
Request.
Path);awaitnext(context);Console.
WriteLine("post");Console.
WriteLine(context.
Response.
StatusCode);}else{awaitnext(context);}});MiddlewareclassespublicclassInspectionMiddleware{privatereadonlyRequestDelegate_next;publicInspectionMiddleware(RequestDelegatenext){_next=next;}publicasyncTaskInvoke(HttpContextcontext){Console.
WriteLine($"request:{context.
Request.
Path}");await_next(context);}}app.
UseMiddleware();DependencyInjectionDI(almost)everywhereStartupctorConfigureServices/ConfigureInlinemiddlewareMiddlewareclassesHostprovideddependencies(e.
g.
IApplicationEnvironment,LoggerFactory)DependenciesprovidedinConfigureServicesDIExamplespublicclassStartup{publicStartup(IApplicationEnvironmentenvironment){/*stuff*/}publicvoidConfigureServices(IServiceCollectionservices,ILoggerFactoryfactory){/*registermorestuff*/}publicvoidConfigure(IApplicationBuilderapp,ISomeServicesomeService){app.
Run(async(HttpContextcontext,IMyCustomServicecustom)=>{awaitcontext.
Response.
WriteAsync(c.
Foo());});}}RegisteringdependenciesNewinstance"percall"NewinstanceperHTTPrequestSingletonservices.
AddTransient();services.
AddSingleton();services.
AddScoped();Example:InjectcurrentuserintodependencypublicvoidConfigureServices(IServiceCollectionservices,ILoggerFactoryfactory){services.
AddTransient(provider=>{varcontext=provider.
GetRequiredService();returnnewMyCustomServiceWithUser(context.
HttpContext.
User);});}Configurationweb.
configisnomoreNewconfigurationsystembasedonkey/valuepairscommandlineenvironmentvariablesJSONfilesINIfilesConfigurationcancomefrommultiplesourceslastsourcewinsExamplepublicclassStartup{publicIConfigurationConfiguration{get;set;}publicStartup(IHostingEnvironmentenv){Configuration=newConfiguration().
AddJsonFile("config.
json").
AddJsonFile($"config.
{env.
EnvironmentName}.
json",optional:true).
AddEnvironmentVariables();}//more}UsingconfigurationpublicclassStartup{IConfiguration_configuration;publicStartup(){_configuration=newConfiguration().
AddJsonFile("config.
json");}publicvoidConfigure(IApplicationBuilderapp){varcopyright=newCopyright{Company=_configuration.
Get("copyright:company"),Year=_configuration.
Get("copyright:year")};app.
Run(async(context)=>{awaitcontext.
Response.
WriteAsync($"Copyright{copyright.
Year},{copyright.
Company}");});}}{"copyright":{"year":"2015","company":"FooIndustries"}}OptionsOptionsisapatternintroducedbyDNXConvertrawname/valuepairsintostronglytypedclassesPutoptionsintoDIsystemHeavilyusedthroughoutASP.
NET5/MVC6ExamplepublicclassStartup{publicvoidConfigureServices(IServiceCollectionservices){//initializeoptionssystemservices.
AddOptions();//de-serializeandregisterconfigsettingsservices.
Configure(_configuration.
GetSubKey("copyright"));}publicvoidConfigure(IApplicationBuilderapp){app.
Run(async(HttpContextcontext,IOptionscopyright)=>{awaitcontext.
Response.
WriteAsync($"Copyright{copyright.
Options.
Year},{copyright.
Options.
Company}");});}}Packaging&DeploymentdnupackCreatesNugetpackagecontainingallcompilationtargetsdnupublishCreatesdeployablewebapplicationSelf-containedforDNXCoreMVC6PackagingMiddlewareRoutingandactionselectionControllerinitializationModelbindingchangesRazorFiltersAPIsErrorhandlingPackagingMVC6ispackagedentirelyasaNuGetMicrosoft.
AspNet.
Mvc{"dependencies":{"Microsoft.
AspNet.
Server.
IIS":"1.
0.
0-beta4","Microsoft.
AspNet.
Server.
WebListener":"1.
0.
0-beta4","Microsoft.
AspNet.
Mvc":"6.
0.
0-beta4"}}MiddlewareMVC6isconfiguredasmiddlewareInConfigureServicesviaAddMvcInConfigureviaUseMvcpublicclassStartup{publicvoidConfigureServices(IServiceCollectionservices){services.
AddMvc();}publicvoidConfigure(IApplicationBuilderapp){app.
UseMvc();}}OverridingdefaultsettingsConfigureMvcusedtooverridedefaultspublicclassStartup{publicvoidConfigureServices(IServiceCollectionservices){services.
AddMvc().
ConfigureMvc(mvc=>{mvc.
AntiForgeryOptions.
CookieName="__antixsrf";mvc.
Filters.
Add(.
.
.
);mvc.
ViewEngines.
Add(.
.
.
);});}}RoutingRoutesconfiguredviaUseMvcRouteParameters.
OptionalfromMVC5removedpublicvoidConfigure(IApplicationBuilderapp){app.
UseMvc(routes=>{routes.
MapRoute("old_default","{controller}/{action}",new{controller="Home",action="Index"});routes.
MapRoute("new_default","{controller=Home}/{action=Index}/{id}");});}ControllersControllerbaseclassstillprovidedActionresultsnowimplementIActionResultControllerbaseprovidesmanyhelperstocreateactionresultsView(),Content(),Created(),HttpNotFound(),HttpUnauthorized(),HttpBadRequest()publicclassHomeController:Controller{publicIActionResultIndex(){returnView();}}AttributeroutingAttributeroutingenabledbydefaultpublicclassHomeController:Controller{//~/or~/hello-world[Route("/")][Route("/hello-world")]publicIActionResultIndex(){returnView();}}AttributeroutingAttributeroutingcanbeappliedtoclass[controller]and[action]actastokens[Route("[controller]/[action]")]publicclassHomeController:Controller{//~/Home/IndexpublicIActionResultIndex(){returnView();}}CombiningRouteattributesRouteattributesinheritpathRoutePrefixfromMVC5removedCanreplaceinheritedpathIftemplatestartswith"/"or"~/"[Route("[controller]")]publicclassHomeController:Controller{//~/Home/hello[Route("hello")]publicIActionResultIndex(){returnView();}//~/hello[Route("/hello")]publicIActionResultIndex2(){returnView();}}Routeparameters[Route]allowsparametersWith{param}syntaxSupportsfiltersWith{param:filter}syntax[Route("[controller]/[action]")]publicclassHomeController:Controller{//GET~/Home/IndexpublicIActionResultIndex(){returnView();}//GET~/Home/Index/5[Route("{id:int}")]publicIActionResultIndex(intid){returnView();}}HTTPmethodbasedroutesHttpGet,HttpPost,HttpPut,HttpDelete,HttpPatchFilteractionmethodonrequestmethodBuildon[Route]semantics[Route("[controller]/[action]")]publicclassHomeController:Controller{//GET~/Home/Index[HttpGet]publicIActionResultIndex(){returnView();}//~/Submit[HttpPost("/Submit")]publicIActionResultSubmit(){returnView();}}AreasAreasdefinedwiththe[Area]attributeUsedtomatchan{area}routeparamAttributeroutingallows[area]routetokenViewsmuststillresideunder~/Areas//Views/publicvoidConfigure(IApplicationBuilderapp){app.
UseMvc(routes=>{routes.
MapRoute("new_default","{area}/{controller=Home}/{action=Index}/{id}");});}[Area("account")]publicclassHomeController:Controller{//.
.
.
}POCOcontrollersControllerclassescanbePOCODiscoveredinprojectsthatreferenceMicrosoft.
AspNet.
Mvc.
*Identifiedby"Controller"classnamesuffix[NonController]disablesDependencyinjectionCaninjectdependenciesintocontrollersviaConstructorPropertiesvia[FromServices]Actionparametersvia[FromServices]publicclassHomeController{IHttpContextAccessor_accessor;publicHomeController(IHttpContextAccessoraccessor){_accessor=accessor;}[FromServices]publicIHttpContextAccessorAccessor{get;set;}publicIActionResultIndex(){returnnewViewResult(){ViewName="Index"};}}Per-requestcontextobjectsCaninjectcertainMVCrequestsobjectsHttpContext,ActionContext,ModelStateDictionary,ViewDataDictionary,etc.
Propertiesvia[Activate]Actionparametersvia[Activate]publicclassHomeController{[Activate]publicViewDataDictionaryViewData{get;set;}[Activate]publicHttpContextContext{get;set;}publicIActionResultIndex(){ViewData["message"]="HelloMVC6!
";returnnewViewResult(){ViewName="Index",ViewData=ViewData};}}ModelbindingchangesImplicitmodelbindingfromroute,query,andformDefaultbindingorderchangedto:1)route,2)query,3)formExplicitmodelbindingpossibleusing:[FromRoute][FromQuery][FromForm][FromHeader][FromServices][FromBody]RazorSharedconfig_ViewStartand_GlobalImportChunks@directivesTagHelpersLikeWebFormscustomcontrolsViewComponentsChildactionreplacementsSharedrazorconfiguration_ViewStart.
cshtmlstillexistsCannoweasilybeputinapplicationrootLayoutassignmentnolongerisfullpath_GlobalImport.
cshtmlisnewSoontobecalled_ViewImports.
cshtmlAllowsforsharing@using,@addTagHelperchunksacrossviewsCanbelocatedinthesameplacesas_ViewStart.
cshtmlRazordirectives(akachunks)@model,@using,@section,@functionsstillexist@helperisgone@inject,@addTagHelperarenewAlso,@awaitHtml.
PartialAsync()isnew@injectAllowsdependencyinjectionintoview@inject@usingMicrosoft.
Framework.
OptionsModel@injectIOptionsConfig@Config.
Options.
SiteNameTaghelpersLikecustomcontrolsforMVCAllowserver-sidecodetoinspecttheelementCanmodifyattributes,tag,and/orcontents@addTagHelper"Namespace.
ClassName,Assembly"Or@addTagHelper"*,Assembly"@addTagHelper"SpanTagHelper,YourProjectName"TaghelperimplementationTagHelperbaseclassClassnameusedtomatchelementOverrideProcessorProcessAsyncInspectelementviaTagHelperContextAlteroutputviaTagHelperOutputpublicclassSpanTagHelper:TagHelper{publicoverridevoidProcess(TagHelperContextcontext,TagHelperOutputoutput){if(context.
AllAttributes.
ContainsKey("emoji")&&"smile"==context.
AllAttributes["emoji"].
ToString()){output.
Attributes.
Add("title","smile");output.
Content.
SetContent(output.
SelfClosing=false;}}}Taghelperimplementation[TargetElement]canbeusedtomatchelementAttributescanbeusedtofilter[HtmlAttributeName]willreadincomingattributeWillremovefromoutput[TargetElement("span",Attributes="emoji")]publicclassEmojiTagHelper:TagHelper{[HtmlAttributeName("emoji")]publicstringEmoji{get;set;}publicoverridevoidProcess(TagHelperContextcontext,TagHelperOutputoutput){if("smile"==Emoji){output.
Attributes.
Add("title","smile");output.
Content.
SetContent(output.
SelfClosing=false;}}}MVCtaghelpersManageYourAccountYou'reinproduction!
ValidationtaghelpersEnteryouremail.
bluehost怎么样?bluehost推出新一代VPS美国云主机!前几天,BlueHost也推出了对应的周年庆活动,全场海外虚拟主机月付2.95美元起,年付送免费的域名和SSL证书,通过活动进入BlueHost中文官网,购买虚拟主机、云虚拟主机和独立服务器参与限时促销。今天,云服务器网(yuntue.com)小编给大家介绍的是新一代VPS美国云主机,美国SSD云主机,2核2G/20GB空间,独立...
星梦云怎么样?星梦云资质齐全,IDC/ISP均有,从星梦云这边租的服务器均可以备案,属于一手资源,高防机柜、大带宽、高防IP业务,一手整C IP段,四川电信,星梦云专注四川高防服务器,成都服务器,雅安服务器。星梦云目前夏日云服务器促销,四川100G高防4H4G10M月付仅60元;西南高防月付特价活动,续费同价,买到就是赚到!点击进入:星梦云官方网站地址1、成都电信年中活动机(成都电信优化线路,封锁...
HostYun 商家以前是玩具主机商,这两年好像发展还挺迅速的,有点在要做点事情的味道。在前面也有多次介绍到HostYun商家新增的多款机房方案,价格相对还是比较便宜的。到目前为止,我们可以看到商家提供的VPS主机包括KVM和XEN架构,数据中心可选日本、韩国、香港和美国的多个地区机房,电信双程CN2 GIA线路,香港和日本机房,均为国内直连线路。近期,HostYun上线低价版美国CN2 GIA ...
asp.net为你推荐
css加载失败css 无法加载360邮箱免费注册360账号-电子邮箱怎么填写?dell服务器bios设置dell R410服务器 bios设置参数如何恢复出厂设置?internetexplorer无法打开Internet Explorer 打不开了360防火墙在哪里设置电脑或电脑360有联网防火墙吗,在哪里设置购物车什么叫淘宝购物车欢迎光临本店宾馆欢迎语都有哪些? 越多越专业越好drupal教程搭建一个多店家订餐网站,可以用joomla,wordpress完成吗?求教程美国独立美国独立战争联系我们代码卸载失败!请联系我们帮助您解决!(错误代码13)--是什么情况
网络域名注册 济南域名注册 德国vps zpanel 美元争夺战 rak机房 nerd 云鼎网络 商务主机 电子邮件服务器 1g空间 爱奇艺vip免费试用7天 新睿云 主机返佣 阿里dns 国内空间 阿里云邮箱个人版 好看的空间 rewritecond ncp是什么 更多