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

青春壹個敷衍的年華 提交于 2020-04-13 18:10:20

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/51539395/loading-views-in-wpf-self-host-asp-net-core-application

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