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.
六一云互联六一云互联为西安六一网络科技有限公司的旗下产品。是一个正规持有IDC/ISP/CDN的国内公司,成立于2018年,主要销售海外高防高速大带宽云服务器/CDN,并以高质量.稳定性.售后相应快.支持退款等特点受很多用户的支持!近期公司也推出了很多给力的抽奖和折扣活动如:新用户免费抽奖,最大可获得500元,湖北新购六折续费八折折上折,全场八折等等最新活动:1.湖北100G高防:新购六折续费八折...
CloudCone 商家也是比较有特点的,和我们熟悉的DO、Vultr、Linode商家均是可以随时删除机器开通的小时计费模式。这个对于有需要短租服务器的来说是比较有性价比的。但是,他们还有一个缺点就是机房比较少,不同于上面几个小时计费服务商可以有多机房可选,如果有这个多机房方案的话,应该更有特点。这次我们可以看到CloudCone闪购活动提供洛杉矶三个促销方案,低至月付1.99美元。商家也可以随...
NameCheap商家如今发布促销活动也是有不小套路的,比如会在提前一周+的时间告诉你他们未来的活,比如这次2021年的首次活动就有在一周之前看到,但是这不等到他们中午一点左右的时候才有正式开始,而且我确实是有需要注册域名,等着看看是否有真的折扣,但是实际上.COM域名力度也就一般需要51元左右,其他地方也就55元左右。当然,这次新年的首次活动不管如何肯定是比平时便宜一点点的。有新注册域名、企业域...
asp.net为你推荐
flashfxp用Flashfxp上传网站的具体步骤苹果appstore宕机为什App Store下载软件 到了一半就停了 不动了asp.net什么叫ASP.NET?cuteftpCuteFTP 和FlashFXP是什么软件,有什么功能,怎样使用?美要求解锁iPhone如何看美版苹果是有锁无锁文档下载请问手机版wps如何把云文档下载到手机上的本地文档?三友网有了解唐山三友集团的吗?大学生待遇如何,工资收入,福利保障,工作环境等等pintang深圳御品堂怎么才能保证他们卖的东西都是有机食品?瞄准的拼音穿越火线枪战王者辅助瞄准什么意思狙击辅助123456hd有很多App后面都有hd是什么意思
广东服务器租用 中国域名网 息壤主机 全球付 java主机 圣迭戈 512au 2017年黑色星期五 警告本网站 双拼域名 hinet 免费dns解析 中国电信宽带测速器 丽萨 监控服务器 云服务器比较 114dns 万网注册 购买空间 免备案cdn加速 更多