0

I've created a ASP.NET Core Web API Controller with React Js App and it on Azure. After sever try I am able to upload on Azure and now I'm getting error on my API. When I click on Customer it does not give me error but there is no data from SQL Database.

Can someone guide me on How to connect DB to my ASP.NET Core Web API or suggest me where am I doing wrong?

I tried post/add data to customer table but I am getting Internal server Error

Here is sql connection string in my appsetting.json

"ConnectionStrings": {
"DevConnection": "jdbc:sqlserver://aspapireact.database.windows.net:1433;database=ReactTask;user=*****;password=*****;encrypt=true;trustServerCertificate=false;hostNameInCertificate=*.database.windows.net;loginTimeout=30;"}

The Startup.cs

namespace RahulTask1
{
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.AddCors(options =>
        {
            options.AddDefaultPolicy(builder =>
            {
                builder.WithOrigins("https://aspapireact.azurewebsites.net")
                .AllowAnyMethod()
                .AllowAnyHeader();
            });
        });
        // In production, the React files will be served from this directory
        services.AddSpaStaticFiles(configuration =>
        {
            configuration.RootPath = "ClientApp/build";
        });

        services.AddDbContext<DatabaseContext>(options =>
        options.UseSqlServer(Configuration.GetConnectionString("DevConnection")));

    }

    // 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();
        }
        else
        {
            app.UseExceptionHandler("/Error");
            // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
            app.UseHsts();
        }

        app.UseHttpsRedirection();
        app.UseStaticFiles();
        app.UseSpaStaticFiles();

        app.UseRouting();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller}/{action=Index}/{id?}");
        });

        app.UseSpa(spa =>
        {
            spa.Options.SourcePath = "ClientApp";

            if (env.IsDevelopment())
            {
                spa.UseReactDevelopmentServer(npmScript: "start");
            }
        });
    }
}
}

And this the API I am trying to call

https://aspapireact.azurewebsites.net/api/Customers

You can see my code on GitHub

https://github.com/rlbrs/ASPAPIReact

In this project you will see the local server connection string but I've updated with above one and same with appserver.json

Rahul Waghmare
  • 125
  • 1
  • 2
  • 9

1 Answers1

0

you can use the configuration builder to the configure services method. To build the key value pair from the appsettings.json on any environment based appsettings file, add following code to the ConfigureServices method (This is not mandatory)

 var builder = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            .AddJsonFile("appsettings.json", optional: false , reloadOnChange : true)
            .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);

And then you read the value for the connection string as

Configuration["ConnectionStrings:DevConnection"]

PS: Any particular reason you are using jdbc connection? why not use the standard dot net based connection string?

  • I don't know but I thought because of React JS. – Rahul Waghmare Apr 01 '20 at 10:26
  • Should I use this Server=tcp:aspapireact.database.windows.net,1433;Initial Catalog=ReactTask;Persist Security Info=False;User ID=***;Password={your_password};MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30; – Rahul Waghmare Apr 01 '20 at 10:27
  • I need some guidance about this project. How to make it working. – Rahul Waghmare Apr 01 '20 at 10:30
  • Still getting this error with tcp connection string POST https://aspapireact.azurewebsites.net/api/Customers 500 (Internal Server Error) – Rahul Waghmare Apr 01 '20 at 10:48
  • Yes It was working fine on local but when I uploaded in Azure no response from DB – Rahul Waghmare Apr 01 '20 at 11:09
  • I have also changed fire wall setting Allow Azure services and resources to access this server Yes – Rahul Waghmare Apr 01 '20 at 11:11
  • okay, another thing to check is to see if you can browse the website(azure web app)?? and also do you have some level of logging in your app? and exception handling? – Mandar Dharmadhikari Apr 01 '20 at 11:27
  • yes i can browse the website and no logging in my app just CRUD functions – Rahul Waghmare Apr 01 '20 at 11:33
  • That means the startup code is running properly. Can you please add some exception handling on your routes and return the exception to the caller, the you will get the exception that was encountered – Mandar Dharmadhikari Apr 01 '20 at 11:47
  • I am getting error on fetch function of react, Whenever I perform CRUD action i am getting error. I am not sure but I think it because of connection string. – Rahul Waghmare Apr 01 '20 at 11:56
  • but you conformed that the code is working on your local machine? I also string suggest to test your APIs in a stand alone manner first and figure out if the issue is in your web api. But add the exception handling and return the error back so that you can examine the exact reason for error – Mandar Dharmadhikari Apr 01 '20 at 11:58
  • I did that now I am getting new error Failed to load resource: the server responded with a status of 500 (URL Rewrite Module Error.) – Rahul Waghmare Apr 02 '20 at 03:36