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

后端 未结 2 1294
难免孤独
难免孤独 2020-12-14 10:27

I\'ve looked for other questions related to this, but none seem to be quite what I\'m looking for.

I have a website running on ASP.NET Core with the new project stru

相关标签:
2条回答
  • 2020-12-14 10:39

    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?

    0 讨论(0)
  • 2020-12-14 10:46

    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));
      
    0 讨论(0)
提交回复
热议问题