C#ASP.NET核心web api

编程入门 行业动态 更新时间:2024-10-25 10:31:33
本文介绍了C#ASP.NET核心web api的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

您好,我正在从ASP.NET Web API迁移到ASP.NET Core并使用核心重新编写以下代码但遇到错误,因为这些代码在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核心;错误 // var rawdata = ConvertToByteArray(Request.Content.ReadAsStreamAsync()。Result) ; //ASP 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核心中获取空引用错误;在ASP 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))); }

解决方案

而不是: services.AddDbContext< ApplicationDbContext>(选项= > options.UseSqlServer(Configuration.GetConnectionString( 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 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 core; error //var rawdata = ConvertToByteArray(Request.Content.ReadAsStreamAsync().Result); //ASP 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 core; works fine in ASP 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")));

The GetConnectionString() method is very clear, it will first look for the ConnectionStrings node then the name. So, don't forget to include ConnectionStrings 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

本文发布于:2023-10-29 07:49:09,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1539134.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:核心   NET   ASP   web   api

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!