C#ASP.NET核心web api [英] C# ASP.NET core web api
问题描述
您好,我正在从ASP.NET Web API迁移到ASP.NET Core并使用.net核心重新编写以下代码但遇到错误,因为这些代码在ASP.NET Web API中正常工作。
public class DataController:Controller
{
private IList< string> errors = new List< string>();
[HttpPost]
[路线( data / import,Name = DataImport)]
public IActionResult Post()
{
var rawdata = ConvertToByteArray(Request.Body); // ASP.net核心;错误
// var rawdata = ConvertToByteArray(Request.Content.ReadAsStreamAsync()。Result) ; //ASP.net web api
var rdrec = Encoding.UTF8.GetString(content).Split( new string [] {Environment.NewLine, @ \ rr},StringSplitOptions.None)。ToList();
importdata(rdrec);
if (errors.Count == 0 )
return 确定( POST);
else
return 确定(错误);
}
私有 void importdata(IList< string>行)
{
// string connectionString = @Data Source = localhost; Initial Catalog = TEST_DB ; Integrated Security = True;
string connectionString = ConfigurationManager.ConnectionStrings [ SQLDBCONN]。ConnectionString; // 将此添加到appsettings.json文件并在ASP.net核心中获取空引用错误;在ASP.net web api中正常工作
var message = 跨度>;
var 数据= 来自行 in 行
让 data = line.Split(' ,')
选择 新 filedata
{
ID =数据[ 0 ],
类型=数据[ 1 ],
状态=数据[ 2 ],
描述=数据[ 3 ]
};
使用(SqlConnection sqldbConnection = new SqlConnection(connectionString))
{
sqldbConnection.Open();
foreach ( var i in 数据)
{
尝试
{
使用(SqlCommand cmd = new SqlCommand( INSERT INTO [ dbo]。[testImport]([ID],[Type],[Status],[Description])VALUES(@ ID,@ Type,@ Status,@ Description),sqldbConnection))
{
cmd.Parameters.AddWithValue( @ ID,i.ID);
cmd.Parameters.AddWithValue( @ Type,i.Type);
cmd.Parameters.AddWithValue( @ Status,i.Status);
cmd.Parameters.AddWithValue( @ Description,i.Description);
cmd.ExecuteNonQuery();
}
}
catch (例外情况)
{
message = ex.StackTrace;
return (message);
}
}
}
}
private byte [] ConvertToByteArray(Stream stream)
{
using (MemoryStream ms = new MemoryStream())
{
stream.CopyTo(ms);
return ms.ToArray();
}
}
}
主要在两个地方遇到错误
1)读取原始数据流。我遇到的问题是当我测试post方法时,我得到了成功消息,但数据没有插入表中。当我调试它时,我看到它只读取标题行而不是行。我的猜测就是把它扔到下面的代码行。
var rawdata = ConvertToByteArray(Request.Body);
2)从appsettings.json设置数据库连接字符串之前我能够从web.config文件中获取连接字符串。
string connectionString = ConfigurationManager.ConnectionStrings [SQLDBCONN]。ConnectionString;
我尝试了什么:
要在运行时获取sql数据库连接字符串,我将把连接字符串放在appsettings.json文件中但不知道如何在控制器中调用它。
appsettings.json
{
的SQLDB:{
的SQLDBCONN:{
的MySQLConnStr:数据源= datamartprd.multco.us\\SQLSVR,2505;初始目录= BISTG_CLOUD_QAT ;用户ID = dbsql_bidm__googleapps_qry;密码= wf#Gd5MZw9hJ;
}
}
}
public void ConfigureServices(IServiceCollection services )
{
services.AddDbContext< ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString(SQLDBCONN)));
}
而不是:
<预郎= C#> services.AddDbContext< ApplicationDbContext>(选项= <跨度类= 代码关键字>> 跨度>
options.UseSqlServer(Configuration.GetConnectionString(<跨度类=代码-string> SQLDBCONN)));
尝试:
services.AddDbContext< ApplicationDbContext>(options = >
options.UseSqlServer(Configuration.GetConnectionString( SQLDB:SQLDBCONN:MySQLConnStr )));
GetConnectionString()
方法非常明确,它将首先查找ConnectionStrings
节点,然后查找名称。所以,不要忘记包含ConnectionStrings
节点或代码将抛出NULL异常错误。
ConnectionStrings:{
SQLDB:{
SQLDBCONN:{
MySQLConnStr:您的数据源
}
}
}
查看我在ASP.NET Core上的文章作为示例:实体框架核心入门:使用Web API和代码优先开发构建ASP.NET核心应用程序
最后,查看官方文件:从ASP.NET Web API迁移到ASP.NET Core
Hi, I am working on migrating from ASP.NET Web API to ASP.NET Core and re-wrote the below code using .net core but run into errors where as this same code works fine in ASP.NET Web API.
public class DataController : Controller
{
private IList<string> errors = new List<string>();
[HttpPost]
[Route("data/import", Name = "DataImport")]
public IActionResult Post()
{
var rawdata = ConvertToByteArray(Request.Body); //ASP.net core; error
//var rawdata = ConvertToByteArray(Request.Content.ReadAsStreamAsync().Result); //ASP.net web api
var rdrec = Encoding.UTF8.GetString(content).Split(new string[] { Environment.NewLine, @"\r" }, StringSplitOptions.None).ToList();
importdata(rdrec);
if (errors.Count == 0)
return Ok("POST");
else
return Ok(errors);
}
private void importdata(IList<string> lines)
{
//string connectionString = @"Data Source=localhost;Initial Catalog=TEST_DB;Integrated Security=True";
string connectionString = ConfigurationManager.ConnectionStrings["SQLDBCONN"].ConnectionString; // Added this to appsettings.json file and get null reference error in ASP.net core; works fine in ASP.net web api
var message = "";
var Data = from line in lines
let data = line.Split(',')
select new filedata
{
ID = data[0],
Type = data[1],
Status = data[2],
Description = data[3]
};
using (SqlConnection sqldbConnection = new SqlConnection(connectionString))
{
sqldbConnection.Open();
foreach (var i in Data)
{
try
{
using (SqlCommand cmd = new SqlCommand("INSERT INTO [dbo].[testImport] ([ID], [Type], [Status], [Description]) VALUES (@ID, @Type, @Status, @Description)", sqldbConnection))
{
cmd.Parameters.AddWithValue("@ID", i.ID);
cmd.Parameters.AddWithValue("@Type", i.Type);
cmd.Parameters.AddWithValue("@Status", i.Status);
cmd.Parameters.AddWithValue("@Description", i.Description);
cmd.ExecuteNonQuery();
}
}
catch (Exception ex)
{
message = ex.StackTrace;
return (message);
}
}
}
}
private byte[] ConvertToByteArray(Stream stream)
{
using (MemoryStream ms = new MemoryStream())
{
stream.CopyTo(ms);
return ms.ToArray();
}
}
}
Primarily run into errors at two places
1) Reading raw datastream. The issue I am running into is when I test the post method I get success message but data is not getting inserted in the table. When I debug it I see it reading just the header line but not the rows. My guess is its throwing me off at the below line of code.
var rawdata = ConvertToByteArray(Request.Body);
2) Setting the database connectionstring from appsettings.json previously I was able to fetch the connectionstring fine from web.config file.
string connectionString = ConfigurationManager.ConnectionStrings["SQLDBCONN"].ConnectionString;
What I have tried:
To get the sql database connectionstring at runtime I am putting the connectionstring in the appsettings.json file but not sure how to call it in the Controller.
appsettings.json
{ "SQLDB": { "SQLDBCONN": { "MySQLConnStr": "Data Source=datamartprd.multco.us\\SQLSVR,2505;Initial Catalog=BISTG_CLOUD_QAT;User Id=dbsql_bidm__googleapps_qry;Password=wf#Gd5MZw9hJ;" } } }
public void ConfigureServices(IServiceCollection services) { services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("SQLDBCONN"))); }
Instead of doing:
services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("SQLDBCONN")));
Try:
services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("SQLDB:SQLDBCONN:MySQLConnStr")));
TheGetConnectionString()
method is very clear, it will first look for theConnectionStrings
node then the name. So, don't forget to includeConnectionStrings
node or the code will throw NULL exception error.
"ConnectionStrings": { "SQLDB": { "SQLDBCONN": { "MySQLConnStr": "your data source" } } }
Check my article on ASP.NET Core for an example: Getting Started with Entity Framework Core: Building an ASP.NET Core Application with Web API and Code First Development
And finally, check the official documenation about: Migrate from ASP.NET Web API to ASP.NET Core
这篇关于C#ASP.NET核心web api的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!