简体   繁体   中英

Loading views in WPF self-host asp.net core application

We need to self-host an Asp.Net Core application in a WPF APP, APIs are working fine but there is some issues loading cshtml views.

Here is our code: Host Builder:

public static class HostBuilder
    {
        private static IWebHost host;

        public static async Task Start()
        {
            if (host == null)
            {
                var ip = System.Net.IPAddress.Parse("127.0.0.1");
                var port = 9388;

                host = new WebHostBuilder()
                   .UseKestrel(options =>
                   {
                       options.Listen(ip, port);
                   })
                   .UseStartup<HostStartup>()
                   .Build();

                await host.RunAsync();
            }
        }

    }

Host startup:

public class HostStartup
    {
        public IConfiguration Configuration { get; }

        public HostStartup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
        }

        public void Configure(IApplicationBuilder app, IHostingEnvironment env, System.IServiceProvider serviceProvider)
        {

            app.UseMvcWithDefaultRoute();
        }
    }

Controller:

[AllowAnonymous]
    [Route("api")]
    public class LoginController : Controller
    {
        [HttpGet]
        [Route("/myview")]
        public ViewResult MyView()
        {
            var v = View("myview");
            return v;
        }

        [HttpGet]
        [Route("test")]
        public IActionResult Test()
        {
            return Ok("Good!");
        }
    }

The url http://127.0.0.1:9388/api/test is working! (web API) But when we navigate to http://127.0.0.1:9388/myview browser shows http error 500.

Am I missing something? There is no exceptions on WPF.

Ok, it's working now! You need to do a few things manually:

1) Migrate your WPF projet to VS2017 format, here is how: How-to migrate Wpf projects to the new VS2017 format (find for @stil answer)

2) Install Asp.net Core And Asp.net Core MVC

3) Edit the csproj again and change the root Sdk attribute from Microsoft.NET.Sdk to Microsoft.NET.Sdk.Razor

4) Point your WPF project to framework 4.6.2, 4.7 > doesn't work!

5) Your cshtml must have the build option "Content", but, the instruction on csproj need to be removed, otherwise, it'll not compile.

Here is an example: https://github.com/alexandrereyes/wpf-aspnetcore-mvc

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM