Skip to main content
 首页 » 编程设计

c#之如何在 azure 上托管和部署 ASP.Net core 2.0 web api

2024年01月13日29mengfanrong

我在 visual studio 2017 中创建了一个解决方案,我在其中创建了以下项目:

  1. 客户端(使用核心 2.1 的 Angular 模板)
  2. 服务器(使用 core 2.0 的 web api)

因为我刚开始在 Azure 上部署我的应用程序。因此,通过使用 Internet 上的引用资料,我成功地在 Azure 上部署了我的客户端应用程序,并且它已启动并运行 https://ebarvo.azurewebsites.net

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

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

据点[OPTIONAL] Step 4: Create your own Web API .我已经在 B2C 设置中注册了我的 web api。这是屏幕截图:

现在根据 this link 注册我的 web api 之后我的第一个问题是如何以及在何处可以在我的应用程序代码中使用我的应用程序客户端 ID?

这里给大家展示一下web api(服务端)config.cs/startup.cs/program.cs文件代码:

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 发布到 azure

第 1 步

第二步

选择现有应用服务后

第 3 步

发布后

我收到这条消息:

如果我通过 postman 发出邮寄请求:

本地运行良好

但是在 azure 上部署后它显示 500 内部服务器错误。

现在我更多地解释我的问题,即什么是正确的方法以及如何在 azure 上托管和部署 ASP.Net core 2.0 webapi? 以及更多我在我的代码或步骤中做错了什么,所以我的服务器没有响应我?我想我在这里解释每一步都是为了向大家展示我正在做什么以及我正在尝试做什么。请在这方面帮助我,我将非常感谢你们。

请您参考如下方法:

我认为你的问题在这里:

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

尝试删除 .UseUrls( … )

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

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