1、沿用上一篇的Asp.Net Core Web API服务,修改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.AddControllers(); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "WebApiService", Version = "v1" }); c.ResolveConflictingActions(apiDescriptions => apiDescriptions.First()); }); services.AddSingleton<UserServer>(new UserServer()); services.AddGrpcClient<TestGrpc.TestGrpcClient>(options => { options.Address = new Uri("http://localhost:5000"); }); services.AddCors(options => { options.AddPolicy("myAllows", policys => { policys.AllowAnyHeader(); policys.AllowAnyMethod(); policys.AllowCredentials(); policys.WithOrigins(new[] { "http://localhost:5005" }); }) ; } ); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseSwagger(); app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "WebApiService v1")); } app.UseRouting(); app.UseCors("myAllows"); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); } }
2、新建Asp.Net Core Web MVC项目
3、修改launchSettings.json
{ "profiles": { "WebApplication1": { "commandName": "Project", "dotnetRunMessages": "true", "launchBrowser": true, "applicationUrl": "http://localhost:5005", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" } } } }
4、修改Index.cshtml
@{ ViewData["Title"] = "Home Page"; } <script src="~/lib/jquery/dist/jquery.min.js"></script> <div class="text-center"> <h1 class="display-4">Welcome</h1> <p>Learn about <a href="https://docs.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.</p> </div> <div id="showApiData"> </div> <div id="showGrpcData"> </div> <script type="text/javascript"> $(function () { $.ajax({ url: "http://localhost:5007/api/MyApi/Get", type: "Get", success: function (data) { var str = ""; alert(JSON.stringify(data)); for (var i = 0; i < data.length; i++) { str += data[i].name; } $("#showApiData").html(str); } }) $.ajax({ url: "http://localhost:5007/api/MyApi/GetGrpc", type: "Get", success: function (data) { var str = ""; alert(JSON.stringify(data)); str = data; $("#showGrpcData").html(str); } }) }) </script>
5、启动Grpc 服务,启动Asp.Net Core Web API 服务,启动MVC项目。