大佬教程收集整理的这篇文章主要介绍了在 .Net Core 3.1 Web API 中将文档上传到 SQL Server 时出错,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个 sql Server 存储过程,用于上传文档并在成功时返回 ID。
我将参数 file_data 存储到 Customer_document_ADD 类中的 byte[] 类型中。
public byte[] file_data { get; set; }
以下是我的仓库代码。
public async Task<int> InsertCustomer_document_ADDResult(Customer_document_ADD customer_document_ADDED)
{
await using(sqlConnection connection = new sqlConnection(_connectionString))
{
connection.open();
// define sqlParameters for the other two params to be passed
var company_IDParam = new sqlParameter("@company_ID",customer_document_ADDED.company_ID);
var customer_IDParam = new sqlParameter("@customer_ID",customer_document_ADDED.customer_ID);
var customer_site_IDParam = new sqlParameter("@customer_site_ID",customer_document_ADDED.customer_site_ID);
var customer_system_IDParam = new sqlParameter("@customer_system_ID",customer_document_ADDED.customer_system_ID);
var @R_202_6186@Param = new sqlParameter("@@R_202_6186@",customer_document_ADDED.@R_202_6186@);
var security_levelParam = new sqlParameter("@security_level",customer_document_ADDED.security_level);
var file_nameParam = new sqlParameter("@file_name",customer_document_ADDED.file_name);
var file_sizeParam = new sqlParameter("@file_size",customer_document_ADDED.file_sizE);
var upload_dateParam = new sqlParameter("@upload_date",customer_document_ADDED.upload_datE);
var document_extParam = new sqlParameter("@document_ext",customer_document_ADDED.document_ext);
var user_codeParam = new sqlParameter("@user_code",customer_document_ADDED.user_codE);
var user_descriptionParam = new sqlParameter("@user_description",customer_document_ADDED.user_description);
var reference1Param = new sqlParameter("@reference1",customer_document_ADDED.reference1);
var reference2Param = new sqlParameter("@reference2",customer_document_ADDED.reference2);
var reference3Param = new sqlParameter("@reference3",customer_document_ADDED.reference3);
var reference4Param = new sqlParameter("@reference4",customer_document_ADDED.reference4);
var file_dataParam = new sqlParameter("@file_data",customer_document_ADDED.file_data);
//if (file_dataParam.Value == null)
//{
// file_dataParam.Value = "";
//}
file_dataParam.sqlDbType = sqlDbType.Image;
// define the output parameter that needs to be retained
// for the ID created when the Stored Procedure executes
// the INSERT command
var document_IDParam = new sqlParameter("@document_ID",sqlDbType.int);
// the direction defines what kind of parameter we're passing
// it can be one of:
// input
// Output
// inputOutput -- which does pass a value to Stored Procedure and retains a new state
document_IDParam.Direction = ParameterDirection.output;
// we can also use context.Database.ExecutesqlCommand() or awaitable ExecutesqlCommandAsync()
// which also produces the same result - but the method is Now marked obSELEte
// so we use ExecutesqlRawAsync() instead
// we're using the awaitable version since GetorcreateuserAsync() method is marked async
await context.Database.ExecutesqlRawAsync(
"EXECUTE [dbo].[Customer_document_ADD_incentive] @company_ID,@customer_ID,@customer_site_ID,@customer_system_ID,@@R_202_6186@,@security_level,@file_name,@file_size,@upload_date,@document_ext,@user_code,@user_description,@reference1,@reference2,@reference3,@reference4,@file_data,@document_ID out",company_IDParam,customer_IDParam,customer_site_IDParam,customer_system_IDParam,@R_202_6186@Param,security_levelParam,file_nameParam,file_sizeParam,upload_dateParam,document_extParam,user_codeParam,user_descriptionParam,reference1Param,reference2Param,reference3Param,reference4Param,file_dataParam,document_IDParam);
// the userIDParam which represents the Output param
// Now holds the ID of the new user and is an Object type
// so we convert it to an Integer and send
return Convert.ToInt32(document_IDParam.value);
}
}
我在 Postman 中收到以下错误。
@H_872_7@microsoft.Data.sqlClIEnt.sqlException (0x80131904): The parameterized query '(@company_ID int,@customer_ID int,@customer_site_ID int,@custome' expects the parameter '@file_data',which was not supplIEd. at Microsoft.Data.sqlClIEnt.sqlConnection.onError(sqlException exception,Boolean breakConnection,Action`1 wrapCloseInAction) at Microsoft.Data.sqlClIEnt.sqlInternalConnection.onError(sqlException exception,Action`1 wrapCloseInAction) at Microsoft.Data.sqlClIEnt.TdsParser.ThrowExceptionAnDWarning(TdsParserStateObject stateObj,Boolean callerHasConnectionLock,Boolean asyncclosE) at Microsoft.Data.sqlClIEnt.TdsParser.TryRun(RunBehavior runBehavior,sqlCommand cmdHandler,sqlDataReader dataStream,BulkcopySimpleResultSet bulkcopyHandler,TdsParserStateObject stateObj,Boolean& dataReady) at Microsoft.Data.sqlClIEnt.sqlCommand.FinishExecuteReader(sqlDataReader ds,RunBehavior runBehavior,String resetOptionsString,Boolean isInternal,Boolean forDescribeParameterEncryption,Boolean shouldCacheForAlwaysEncrypted) at Microsoft.Data.sqlClIEnt.sqlCommand.CompleteAsyncExecuteReader(Boolean isInternal,Boolean forDescribeParameterEncryption) at Microsoft.Data.sqlClIEnt.sqlCommand.InternalEndExecuteNonquery(IAsyncResult asyncResult,String endMethod) at Microsoft.Data.sqlClIEnt.sqlCommand.endExecuteNonqueryInternal(IAsyncResult asyncResult) at Microsoft.Data.sqlClIEnt.sqlCommand.endExecuteNonqueryAsync(IAsyncResult asyncResult) at System.Threading.Tasks.TaskFactory`1.FromAsyncCoreLogic(IAsyncResult iar,Func`2 endFunction,Action`1 endAction,Task`1 promise,Boolean requiresSynchronization) --- End of stack trace from prev@R_@R_502_6940@_6928@s LOCATIOn where exception was thrown --- at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteNonqueryAsync(RelationalCommandParameterObject parameterObject,CancellationToken cancellationToken) at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteNonqueryAsync(RelationalCommandParameterObject parameterObject,CancellationToken cancellationToken) at Microsoft.EntityFrameworkCore.RelationalDatabaseFacadeExtensions.ExecutesqlRawAsync(DatabaseFacade databaseFacade,String sql,IEnumerable`1 parameters,CancellationToken cancellationToken) at WebAPI.Repository.Customer_document_ADDRepository.InsertCustomer_document_ADDResult(Customer_document_ADD customer_document_ADDED) in C:\Users\CStith\source\code\project\WebAPI\WebAPI\Repository\Customer_document_ADDRepository.cs:line 73 at WebAPI.Repository.Customer_document_ADDRepository.InsertCustomer_document_ADDResult(Customer_document_ADD customer_document_ADDED) in C:\Users\CStith\source\code\project\WebAPI\WebAPI\Repository\Customer_document_ADDRepository.cs:line 97 at WebAPI.Controllers.Customer_document_ADDController.InsertCustomer_document_ADDResult(Customer_document_ADD customer_document_ADDED) in C:\Users\CStith\source\code\project\WebAPI\WebAPI\Controllers\Customer_document_ADDController.cs:line 38 at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.TaskOfIActionResultExecutor.Execute(IActionResultTypeMapper mapper,ObjectMethodExecutor executor,Object controller,Object[] arguments) at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeActionMethodAsync>g__Awaited|12_0(ControllerActionInvoker invoker,ValueTask`1 actionResultValueTask) at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeNextActionFilterasync>g__Awaited|10_0(ControllerActionInvoker invoker,Task lastTask,State next,Scope scope,Object state,Boolean isCompleted) at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context) at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next,Scope& scope,Object& state,Boolean& isCompleted) at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeInnerFilterasync>g__Awaited|13_0(ControllerActionInvoker invoker,Boolean isCompleted) at Microsoft.AspNetCore.Mvc.Infrastructure.resourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|19_0(resourceInvoker invoker,Boolean isCompleted) at Microsoft.AspNetCore.Mvc.Infrastructure.resourceInvoker.<InvokeAsync>g__Awaited|17_0(resourceInvoker invoker,Task task,Idisposable scopE) at Microsoft.AspNetCore.RoutIng.EndpointMIDdleware.<Invoke>g__AwaitrequestTask|6_0(Endpoint endpoint,Task requestTask,ILogger logger) at Microsoft.AspNetCore.Authorization.AuthorizationMIDdleware.Invoke(httpContext context) at Microsoft.AspNetCore.Authentication.AuthenticationMIDdleware.Invoke(httpContext context) at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMIDdleware.Invoke(httpContext context) ClIEntConnectionID:e8f735f0-1ab5-4d53-9ead-01df3ee63c2e Error number:8178,State:1,Class:16
除文件之外的所有其他值都被捕获。我在调试器中得到一个空值。为什么我无法将文件上传到数据库?提前致谢。
首先,默认模型绑定系统无法将文件绑定到byte[]属性。如果要将文件绑定到btye[],可以使用ByteArraymodelBinder
,这里是一个official link。
另外,如果你不介意改变file_data的类型,你可以使用
public IFormFile file_data { get; set; }
然后您可以使用 @H_872_7@memoryStream 将其转换为 byte[] 类型。这是关于在 .net core 中上传文件的 official link。
以上是大佬教程为你收集整理的在 .Net Core 3.1 Web API 中将文档上传到 SQL Server 时出错全部内容,希望文章能够帮你解决在 .Net Core 3.1 Web API 中将文档上传到 SQL Server 时出错所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。