简体   繁体   中英

How to Host and Deploy ASP.Net core 2.0 webapi on azure?

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

  1. Client (Angular Template using core 2.1)
  2. Server (web api using core 2.0)

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

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

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.

在此处输入图片说明

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?

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();
}

Now, If I publish my webapi to azure like below

Step # 1

Step # 2

After selecting existing app service 在此处输入图片说明

Step # 3

After publishing

在此处输入图片说明

I got this message:

在此处输入图片说明

and If I make a post request through post man:

on local its running fine

在此处输入图片说明

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

在此处输入图片说明

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();

try to delete .UseUrls( … )

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

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

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