DOT NET CORE_API_L1 DB連線?
來源參考:https://www.youtube.com/watch?v=_SprpIlxug8
~appsettings.json
{
"Logging": {
"LogLevel": {
"Default": "Warning"
}
},
//連線字串
"ConnectionStrings":{
"DefaultConnection":"Data Source=127.0.0.1;Initial Catalog=DBJosh;User ID=Josh;Password=123456"
},
"AllowedHosts": "*"
}
-----------------------------------------
~Startup.cs
using *;
//**************手動補上 命名空間
using Microsoft.Extensions.Configuration; //ConfigurationBuilder 會用到
using System.IO; //Directory 會用到
using System.Data.SqlClient; //SQL
using System.Text.Encodings.Web; //HtmlEcoder會用到(處理中文編碼)
//**************************END
namespace webapi
{
public class Startup
{
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
}
// 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.Run(async (context) =>
{
// await context.Response.WriteAsync("Hello World!");
//連線字串在appsetting.json 裡
var configurationBuilder = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("appsettings.json");
IConfiguration config = configurationBuilder.Build();
string connectionString = config["ConnectionStrings:DefaultConnection"];
var Conn = new SqlConnection(connectionString);
Conn.Open();
var Com = new SqlCommand("SELECT u_area FROM tb_User WHERE u_no = @u_no", Conn);
Com.Parameters.AddWithValue("u_no", 1);
using (SqlDataReader dr = Com.ExecuteReader()) {
while (dr.Read()) {
//1.中文亂解決--瀏覽器改UTF8
var title = dr["u_area"];
await context.Response.WriteAsync("<br />"+ title +"<hr />");
//2.中文亂碼解決 -- 不用修改瀏覽器--請加入 using System.Text.Encodings.Web;
var title2 = HtmlEncoder.Default.Encode(dr["u_area"].ToString());
await context.Response.WriteAsync("<br />" + title2+ "<hr />");
}
}
Conn.Close();
});
}
}
}
沒有留言:
張貼留言