Using C# 7 features inside of a View in an ASP.NET MVC Core project

天涯浪子 提交于 2019-11-28 21:29:02
Julien Couvreur

Could you try the following (recommended by folks on the ASP.NET core team):

  1. Install the Microsoft.CodeAnalysis.CSharp (version 2.0.0) and System.ValueTuple (version 4.3.0) packages
  2. In Startup.cs, in the ConfigureServices method, configure Razor to use C# 7 by doing the following:

    services.AddMvc().AddRazorOptions(options =>
         options.ParseOptions = new CSharpParseOptions(LanguageVersion.CSharp7));
    

So I found out that there are some compilation options exposed that you call call in the ConfigureServices() call.

public void ConfigureServices(IServiceCollection services)
{
    // Add framework services.
    services.AddMvc().AddRazorOptions(x => x.ParseOptions.WithLanguageVersion(LanguageVersion.CSharp7));
}

Problem is LanguageVersion.CSharp7 gives an error if you don't add Roslyn. So I'm assuming that is necessary.

After adding Roslyn, everything compiles fine, BUT the view still gives an error.

@{
    //My view code
    string s = "1";
    int.TryParse(s, out int i);
}

So if MVC exposes a RazorOptions that you can use to specify the language version, why is it not honored?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!