如何在Azure上托管和部署ASP.Net Core 2.0 Webapi? [英] How to Host and Deploy ASP.Net core 2.0 webapi on azure?

查看:68
本文介绍了如何在Azure上托管和部署ASP.Net Core 2.0 Webapi?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在Visual Studio 2017中创建了一个解决方案,其中创建了以下项目:

I've created a solution in visual studio 2017 in which I've created below projects:

  1. 客户端(使用核心2.1的角度模板)
  2. 服务器(使用核心2.0的网络api)

由于我是刚开始在天蓝色的环境中部署我的应用程序,因此,通过使用Internet上的引用,我成功地在Azure上部署了我的客户端应用,并且该应用已启动并在 https://ebarvo.azurewebsites.net

As I'm new to deploy my app on azure. So, by using references on internet I successfully deploy my client app on azure and it is up and running on https://ebarvo.azurewebsites.net

现在,我需要做的是在Azure上部署服务器.

and now What I need to do is to deploy my server on azure.

我已经在我的Web api中实现了IdentityServer 4资源所有者密码授予客户端.在我的本地iis服务器上,我的(客户端和Web API)服务器应用程序正在单独运行.

I've implemented IdentityServer 4 Resource Owner Password Grant Client in my web api. On my local iis server my (client and web api) server apps is running individually.

根据指向> [可选]第4步:创建自己的Web API .我已经在B2C设置中注册了我的Web API.这是屏幕截图:

According to point [OPTIONAL] Step 4: Create your own Web API. I've register my web api in the B2C settings. Here is the screen shot:

现在根据

Now after registering my web api according to this link my first question is how and where I can use my Application Client ID in my application code?

在这里,我将向您展示Web api(服务器)config.cs/startup.cs/program.cs文件代码:

Here I'll show you web api (server) config.cs / startup.cs / program.cs file code:

config.cs

public class Config
{
    public static IEnumerable<IdentityResource> GetIdentityResources()
    {
        return new List<IdentityResource>
        {
            new IdentityResources.OpenId(),
            new IdentityResources.Email(),
            new IdentityResources.Profile(),
        };
    }


    public static IEnumerable<ApiResource> GetApiResources()
    {
        return new List<ApiResource>
        {
            new ApiResource("api1", "My API")
        };
    }

    public static IEnumerable<Client> GetClients()
    {
        // client credentials client
        return new List<Client>
        {

            // resource owner password grant client
            new Client
            {
                ClientId = "ro.angular",
                AllowedGrantTypes = GrantTypes.ResourceOwnerPassword,

                ClientSecrets =
                {
                    new Secret("secret".Sha256())
                },
                AllowedScopes = {
                    IdentityServerConstants.StandardScopes.OpenId,
                    IdentityServerConstants.StandardScopes.Profile,
                    IdentityServerConstants.StandardScopes.Email,
                    IdentityServerConstants.StandardScopes.Address,
                    "api1"
                },
                AllowOfflineAccess = true,
                AccessTokenLifetime = 1
            }
        };
    }
}

Startup.cs

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddDbContext<ApplicationDbContext>(options =>
           options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

        services.AddIdentity<ApplicationUser, IdentityRole>()
            .AddEntityFrameworkStores<ApplicationDbContext>()
            .AddDefaultTokenProviders();

        services.AddIdentityServer()
            .AddDeveloperSigningCredential()
            .AddInMemoryPersistedGrants()
            .AddInMemoryIdentityResources(Config.GetIdentityResources())
            .AddInMemoryApiResources(Config.GetApiResources())
            .AddInMemoryClients(Config.GetClients())
            .AddAspNetIdentity<ApplicationUser>();

        services.AddCors(options =>
        {
            options.AddPolicy("AllowClient",
                builder => builder.WithOrigins("https://localhost:44335")
                                  .AllowAnyHeader()
                                  .AllowAnyMethod());
        });

        services.AddMvc();


        services.AddAuthentication(options =>
        {
            options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
        })
        .AddJwtBearer(options =>
        {
            // base-address of your identityserver
            options.Authority = "http://localhost:52718/";

            // name of the API resource
            options.Audience = "api1";

            options.RequireHttpsMetadata = false;
        });
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        app.UseIdentityServer();
        app.UseAuthentication();
        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "areas",
                template: "{area:exists}/{controller=Home}/{action=Index}/{id?}"
            );
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });
    }
}

Program.cs

public class Program
{
    public static void Main(string[] args)
    {
        BuildWebHost(args).Run();
    }

    public static IWebHost BuildWebHost(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseUrls("http://localhost:52718/")
            .UseStartup<Startup>()
            .Build();
}

现在,如果我将webapi发布为如下所示的天蓝色

Now, If I publish my webapi to azure like below

步骤1

第2步

选择现有的应用程序服务后

After selecting existing app service

第3步

发布后

我收到此消息:

如果我通过邮递员发出发帖请求:

and If I make a post request through post man:

在本地运行正常

但是在azure上部署后,它显示了500个内部服务器错误.

but after deployment on azure its shows me 500 internal server error.

现在,我将进一步解释我的问题:什么是正确的方法以及如何在azure上托管和部署ASP.Net core 2.0 webapi? 以及我在代码或步骤中做错了什么,以便服务器未响应我?我想我在这里解释了每个步骤,向您展示了我在做什么和我要做什么.请帮助我,我将非常感谢你们.

Now I more explain my question that what is the right way and how to Host and Deploy ASP.Net core 2.0 webapi on azure? and further more what I'm doing wrong in my code or in my steps so my server is not responding me? I think I explain every single step here to show you people what I'm doing and what I'm try to do. Please help me on this I'll be very thankful to you all.

推荐答案

我认为您的问题在这里:

I think your problem is here :

public static IWebHost BuildWebHost(string[] args) =>
    WebHost.CreateDefaultBuilder(args)
        .UseUrls("http://localhost:52718/")
        .UseStartup<Startup>()
        .Build();

尝试删除.UseUrls(…)

try to delete .UseUrls( … )

public static IWebHost BuildWebHost(string[] args) =>
    WebHost.CreateDefaultBuilder(args)
        .UseStartup<Startup>()
        .Build();

我从未使用过该命令,并且在Azure上发布时也从未遇到过问题.如果需要在本地计算机上指定端口,请进入项目"属性->调试"->"Web服务器设置"->应用程序URL"

I never used that command and never had a problem when I publish on azure, If you need to specify a port on the local machine, go on Project properties -> Debug -> Web Server Settings -> App URL

这篇关于如何在Azure上托管和部署ASP.Net Core 2.0 Webapi?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆