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.
主机参考最新消息:JustHost怎么样?JustHost服务器好不好?JustHost好不好?JustHost是一家成立于2006年的俄罗斯服务器提供商,支持支付宝付款,服务器价格便宜,200Mbps大带宽不限流量,支持免费更换5次IP,支持控制面板自由切换机房,目前JustHost有俄罗斯5个机房可以自由切换选择,最重要的还是价格真的特别便宜,最低只需要87卢布/月,约8.5元/月起!just...
ftech怎么样?ftech是一家越南本土的主机商,成立于2011年,比较低调,国内知道的人比较少。FTECH.VN以极低的成本提供高质量服务的领先提供商之一。主营虚拟主机、VPS、独立服务器、域名等传统的IDC业务,数据中心分布在河内和胡志明市。其中,VPS提供1G的共享带宽,且不限流量,还可以安装Windows server2003/2008的系统。Ftech支持信用卡、Paypal等付款,但...
greencloudvps怎么样?greencloudvps是一家国外主机商,VPS数据中心多,之前已经介绍过多次了。现在有几款10Gbps带宽的特价KVM VPS,Ryzen 3950x处理器,NVMe硬盘,性价比高。支持Paypal、支付宝、微信付款。GreenCloudVPS:新加坡/美国/荷兰vps,1核@Ryzen 3950x/1GB内存/30GB NVMe空间/1TB流量/10Gbps...
asp.net为你推荐
支持ipadcss加载失败网易邮箱登陆显示CSS加载失败,怎么办?急,在线等。360arp防火墙在哪360ARP防火墙宜人贷官网宜人财富怎么样?discuz伪静态求虚拟主机Discuz 伪静态设置方法香港空间香港有什么标志性建筑?discuz7.2求解答Discuz!7.2 论坛怎么设置邮件管理系统什么邮件管理软件最适合有分公司的企业?网站流量统计代码网站访问量统计代码 不要http://www.51.la/这样挂在别的网站下的 需要自己可以单独建个网页的那种, 谢谢ftp帐号ftp账号是什么
80vps 星星海 vmsnap3 evssl 789电视网 美国网站服务器 电信虚拟主机 超级服务器 双12 彩虹云 无限流量 帽子云排名 iki 攻击服务器 免费获得q币 paypal登陆 shuangshiyi sockscap怎么用 万网空间价格 1000元电脑主机配置 更多