Send Stream in HttpResponseMessage instead of raw file - asp.net-web-api2

I have a requirement of sending the file stream/stream as response in webapi from odata.
Below is the code of API
public async Task<HttpResponseMessage> GetDocumentFiles()
{
var tskk = context.BaseUri;
sb.Append(context.BaseUri)
.Append("FILES(tNumber='")
.Append("1")
.Append("',Type='")
.Append("2")
.Append("',Application='")
.Append("a")
.Append("')/$value");
var queryUrl = sb.ToString();
var req = WebRequest.Create(queryUrl);
var response = req.GetResponse();
using (var res = (WebResponse)req.GetResponse())
{
Stream reader = (Stream)res.GetResponseStream();
return reader;
}
}
but, when I run the below code using postman i am getting the exception. Any ways to send the stream of file without downloading the file to any location. So that, the clients who access this method should be able to download the file using this response.
Exception received:
"$id": "1",
"Message": "An error has occurred.",
"ExceptionMessage": "The 'ObjectContent`1' type failed to serialize the response body for content type 'application/json; charset=utf-8'.",
"ExceptionType": "System.InvalidOperationException",
"StackTrace": null,
"InnerException": {
"$id": "2",
"Message": "An error has occurred.",
"ExceptionMessage": "Error getting value from 'Length' on 'System.Net.ConnectStream'.",
"ExceptionType": "Newtonsoft.Json.JsonSerializationException",
"StackTrace": " at Newtonsoft.Json.Serialization.DynamicValueProvider.GetValue(Object target)\r\n at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.CalculatePropertyValues(JsonWriter writer, Object value, JsonContainerContract contract, JsonProperty member, JsonProperty property, JsonContract& memberContract, Object& memberValue)\r\n at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject(JsonWriter writer, Object value, JsonObjectContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)\r\n at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)\r\n at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.Serialize(JsonWriter jsonWriter, Object value, Type objectType)\r\n at Newtonsoft.Json.JsonSerializer.SerializeInternal(JsonWriter jsonWriter, Object value, Type objectType)\r\n at System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.WriteToStream(Type type, Object value, Stream writeStream, Encoding effectiveEncoding)\r\n at System.Net.Http.Formatting.JsonMediaTypeFormatter.WriteToStream(Type type, Object value, Stream writeStream, Encoding effectiveEncoding)\r\n at System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.WriteToStream(Type type, Object value, Stream writeStream, HttpContent content)\r\n at System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.WriteToStreamAsync(Type type, Object value, Stream writeStream, HttpContent content, TransportContext transportContext, CancellationToken cancellationToken)\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Web.Http.WebHost.HttpControllerHandler.<WriteBufferedResponseContentAsync>d__1b.MoveNext()",
"InnerException": {
"$id": "3",
"Message": "An error has occurred.",
"ExceptionMessage": "This stream does not support seek operations.",
"ExceptionType": "System.NotSupportedException",
"StackTrace": " at System.Net.ConnectStream.get_Length()\r\n at GetLength(Object )\r\n at Newtonsoft.Json.Serialization.DynamicValueProvider.GetValue(Object target)"
}
}
Thanks,
Namitha

Related

Flutter web: How to upload Image to ASP .NET Core web API?

I have an API which is for a CMS that can change my entire 'AboutUs' web page. The following was the Data Model that holds all the contents of that 'About Us' webpage.
I have a Future method that goes this way to update the 'About Us' webpage contents within database only. (via ASP.Net Core web API)
Future updateAboutUsContent() async
Future<AboutUsContextModel> updateAboutUsContent(
String title,
String context,
String subcontext,
PlatformFile imageId,
) async {
final abUC =
await http.put(Uri.parse(urlAddress + "/api/AboutUsContextModels/2"),
headers: <String, String>{
"Content-Type": "multipart/form-data;charset=UTF-8",
},
body: jsonEncode(<String, dynamic>{
"title": title,
"context": context,
"subContext": subcontext
}));
final request = http.MultipartRequest(
"POST", Uri.parse(urlAddress + "/api/AboutUsContextModels/2"));
request.files.add(http.MultipartFile(
"imageFile",
imageId.readStream,
imageId.size,
filename: imageId.name.split("/").last);
var resp = await request.send();
String response = await resp.stream.bytesToString();
print("==================\nThis is the response:\n=================" +
response);
}
if (abUC.statusCode == 200) {
//If the server did return a 200 Created All green post
//then parse the JSON
return AboutUsContextModel.fromJson(jsonDecode(abUC.body));
} else if (abUC.statusCode == 400) {
throw Exception('Error code was 400. About Us Content Not Foun');
} else {
throw Exception('Nothing About Us Content created in Flutter');
}
}
And This Future will call the ASP web API which is as below:
[HttpPut("{id}")]
public async Task<ActionResult<AboutUsContextModel>> PutAboutUsContent(int id, string title, string context, string subcontext, IFormFile imageFile)
{
AboutUsContextModel abUC = await _context.AboutUsContextModel.Include(lim => lim.Image).FirstOrDefaultAsync(limy => limy.AboutUs_Context_Id == id);
if(abUC == null)
{
return BadRequest("No such About Us Content!");
}
if(imageFile != null)
{
ImageModel imgfrmDB = abUC.Image;
if(imgfrmDB != null)
{
string cloudDomaim = "https://privacy-web.conveyor.cloud";
string uploadDrcty = _webEnvr.WebRootPath + "\\Images\\";
if (!Directory.Exists(uploadDrcty))
{
Directory.CreateDirectory(uploadDrcty);
}
string filePath = uploadDrcty + imageFile.FileName;
using (var fileStream = new FileStream(filePath, FileMode.Create))
{
await imageFile.CopyToAsync(fileStream);
await fileStream.FlushAsync();
}
using (var memoryStream = new MemoryStream())
{
await imageFile.CopyToAsync(memoryStream);
imgfrmDB.Image_Byte = memoryStream.ToArray();
}
imgfrmDB.ImagePath = cloudDomaim + "/Images/" + imageFile.FileName;
imgfrmDB.Modify_By = "CMS Admin";
imgfrmDB.Modity_dt = DateTime.Now;
}
}
abUC.Title = title;
abUC.Context = context;
abUC.SubContext = subcontext;
abUC.Modify_By = "CMS Admin";
abUC.Modity_dt = DateTime.Now;
_context.Entry(abUC).State = EntityState.Modified;
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!AboutUsContextModelExists(abUC.AboutUs_Context_Id))
{
return NotFound();
}
else
{
throw;
}
}
return Ok("About Us Content Delivered, Edit Successful");
}
Unfortunately when I run the code, the following errors only shows:
TypeError: Cannot read properties of null (reading 'listen')
at byte_stream.ByteStream.new.listen (http://localhost:60452/dart_sdk.js:36349:31)
at _StreamControllerAddStreamState.new._AddStreamState.new (http://localhost:60452/dart_sdk.js:37160:37)
at new _StreamControllerAddStreamState.new (http://localhost:60452/dart_sdk.js:37191:53)
at _AsyncStreamController.new.addStream (http://localhost:60452/dart_sdk.js:36687:24)
at _AsyncStarImpl.new.addStream (http://localhost:60452/dart_sdk.js:33462:46)
at multipart_request.MultipartRequest.new._finalize (http://localhost:60452/packages/http/src/multipart_request.dart.lib.js:352:22)
at _finalize.next (<anonymous>)
at _AsyncStarImpl.new.runBody (http://localhost:60452/dart_sdk.js:33416:40)
at Object._microtaskLoop (http://localhost:60452/dart_sdk.js:40808:13)
at _startMicrotaskLoop (http://localhost:60452/dart_sdk.js:40814:13)
at http://localhost:60452/dart_sdk.js:36279:9
I used breakpoints to examine each of the lines to track where is the null (in the Flutter's updateAboutUsContent() Future), which this line
final abUC =
await http.put(Uri.parse(urlAddress + "/api/AboutUsContextModels/2"),
headers: <String, String>{
"Content-Type": "multipart/form-data;charset=UTF-8",
},
body: jsonEncode(<String, dynamic>{
"title": title,
"context": context,
"subContext": subcontext,
// 'imageFile': imageId
}));
and this line,
final request = http.MultipartRequest(
"POST", Uri.parse(urlAddress + "/api/AboutUsContextModels/2"));
The 'PlatformFile imageFile' receives the imageFile. It shows the filename, bytes,... all those in the VS Code 'Run and Debug'.
The 'PlatformFile imageFile' still gets the image file, but until this line
request.files.add(http.MultipartFile(
"imageFile",
imageId.readStream,
imageId.size,
filename: imageId.name.split("/").last);
it still execute this line but after that the aforementioned TypeError shows.
It seems that, MAYBE
http.MultipartFile(
"imageFile",
imageId.readStream,
imageId.size,
filename: imageId.name.split("/").last)
↑↑something here was wrong.↑↑
Referring to the first two codes I pasted at first, i.e. updateAboutUsContent(), and PutAboutUsContent() located in the Web API, Can I know
Where did I done wrong?
How can I correct my 'updateAboutUsContent()' method, so that it can connect and 'PUT' data to the 'PutAboutUsContent()' in the .Net Core web API?
How can I convert Flutter's 'PlatformFile' to ASP's 'IFormFile' so that it binds to the corresponding argument that accepts the imageFile?
I'm very new to Flutter web, ASP.NET Core 5.0 web API, and really don't have any idea/concepts about how to upload images to the ASP.NET from flutter web, so something in my updateAboutUsContent() in the Flutter may wrote wrong.
I have tested the PutAboutUsContent() situated in the Web API using Swagger UI, nothing there was wrong, and I was prohibited to change the codes there, I just can use it.
So, I plead. Is there someone could lend a hand, please?
UPDATE
Now the Future updateAboutUsContent() async is changed to this:
Future<AboutUsContextModel> putAboutUsContent(
String title,
String context,
String subcontext,
PlatformFile imageId,
) async {
final abUC =
await http.put(Uri.parse(urlAddress + "/api/AboutUsContextModels/2"),
headers: <String, String>{
"Content-Type": "multipart/form-data;charset=UTF-8",
},
body: jsonEncode(<String, dynamic>{
"title": title,
"context": context,
"subContext": subcontext,
// 'imageFile': imageId
}));
final request = http.MultipartRequest(
"PUT", Uri.parse(urlAddress + "/api/AboutUsContextModels/2"));
var fileadded =
new http.MultipartFile("imageFile",
imageId.readStream,
imageId.size,
filename: imageId.name);
if (fileadded != null) {
request.headers
.addAll(<String, String>{"Content-Type": "multipart/form-data"});
request.files.add(fileadded);
var resp = await request.send();
String response = await resp.stream.bytesToString();
print("==================\nThis is the response:\n=================" +
response);
}
if (abUC.statusCode == 200) {
//If the server did return a 200 Created All green post
//then parse the JSON
return AboutUsContextModel.fromJson(jsonDecode(abUC.body));
} else if (abUC.statusCode == 400) {
throw Exception('Error code was 400. About Us Content Not Foun');
} else {
throw Exception('Nothing About Us Content created in Flutter');
}
}
And the Future method can properly go until to the if(statusCode ==??) there, however, it still returns 400.
Now, the console appears:
==================
This is the response:
=================Microsoft.EntityFrameworkCore.DbUpdateException: An error occurred while updating the entries. See the inner exception for details.
---> Npgsql.PostgresException (0x80004005): 23502: null value in column "Title" of relation "AboutUs_Context" violates not-null constraint
at Npgsql.NpgsqlConnector.<ReadMessage>g__ReadMessageLong|194_0(NpgsqlConnector connector, Boolean async, DataRowLoadingMode dataRowLoadingMode, Boolean readingNotifications, Boolean isReadingPrependedMessage)
at Npgsql.NpgsqlDataReader.NextResult(Boolean async, Boolean isConsuming, CancellationToken cancellationToken)
at Npgsql.NpgsqlCommand.ExecuteReader(CommandBehavior behavior, Boolean async, CancellationToken cancellationToken)
at Npgsql.NpgsqlCommand.ExecuteReader(CommandBehavior behavior, Boolean async, CancellationToken cancellationToken)
at Npgsql.NpgsqlCommand.ExecuteDbDataReaderAsync(CommandBehavior behavior, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReaderAsync(RelationalCommandParameterObject parameterObject, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReaderAsync(RelationalCommandParameterObject parameterObject, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.ExecuteAsync(IRelationalConnection connection, CancellationToken cancellationToken)
Exception data:
Severity: ERROR
SqlState: 23502
MessageText: null value in column "Title" of relation "AboutUs_Context" violates not-null constraint
Detail: Detail redacted as it may contain sensitive data. Specify 'Include Error Detail' in the connection string to include this information.
SchemaName: WebContext
TableName: AboutUs_Context
ColumnName: Title
File: d:\pginstaller_13.auto\postgres.windows-x64\src\backend\executor\execmain.c
Line: 1953
Routine: ExecConstraints
--- End of inner exception stack trace ---
at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.ExecuteAsync(IRelationalConnection connection, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.ExecuteAsync(IEnumerable`1 commandBatches, IRelationalConnection connection, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.ExecuteAsync(IEnumerable`1 commandBatches, IRelationalConnection connection, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.ExecuteAsync(IEnumerable`1 commandBatches, IRelationalConnection connection, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChangesAsync(IList`1 entriesToSave, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChangesAsync(DbContext _, Boolean acceptAllChangesOnSuccess, CancellationToken cancellationToken)
at Npgsql.EntityFrameworkCore.PostgreSQL.Storage.Internal.NpgsqlExecutionStrategy.ExecuteAsync[TState,TResult](TState state, Func`4 operation, Func`4 verifySucceeded, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.DbContext.SaveChangesAsync(Boolean acceptAllChangesOnSuccess, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.DbContext.SaveChangesAsync(Boolean acceptAllChangesOnSuccess, CancellationToken cancellationToken)
at Privacy_Web.Controllers.AboutUsContextModelsController.PutAboutUsContent(Int32 id, String title, String context, String subcontext, IFormFile imageFile) in D:\distributor_dashboard_v2\Privacy_Web\privacy_web_backend\Privacy_Web\Controllers\AboutUsContextModelsController.cs:line 224
at lambda_method299(Closure , Object )
at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.AwaitableObjectResultExecutor.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, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResourceFilter>g__Awaited|24_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|19_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, 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 Swashbuckle.AspNetCore.SwaggerUI.SwaggerUIMiddleware.Invoke(HttpContext httpContext)
at Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.Invoke(HttpContext httpContext, ISwaggerProvider swaggerProvider)
at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
HEADERS
=======
Accept: */*
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9
Connection: close
Content-Length: 263429
Content-Type: multipart/form-data; boundary=dart-http-boundary-zMVNRV2ehRqP4TYkdPpFn.dOrsckK2tfoxBV_s6z5coua9ye0+m
Host: localhost:44395
Referer: http://localhost:63925/
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.69 Safari/537.36
sec-ch-ua: "Google Chrome";v="95", "Chromium";v="95", ";Not A Brand";v="99"
sec-ch-ua-mobile: ?0
sec-ch-ua-platform: "Windows"
origin: http://localhost:63925
sec-fetch-site: cross-site
sec-fetch-mode: cors
sec-fetch-dest: empty
x-server-sni: haproxy.privacy-web-kb5.conveyor.cloud
x-forwarded-for: (***IP address here, censored to be seen***)
When the first two lines of the updateAboutUsContent() method was executed, ie.
final abUC =
await http.put(Uri.parse(urlAddress + "/api/AboutUsContextModels/2"),
headers: <String, String>{
"Content-Type": "multipart/form-data;charset=UTF-8",
},
body: jsonEncode(<String, dynamic>{
"title": title,
"context": context,
"subContext": subcontext,
// 'imageFile': imageId
}));
final request = http.MultipartRequest(
"PUT", Uri.parse(urlAddress + "/api/AboutUsContextModels/2"));
The following shows:
where the readStream returns: Instance of '_ControllerStream<List>'.
So I think this was the reason statusCode 400 was returned.
So, how should I solve it? Or if I wrongly identified the issue causing the error, then where can I improved?
You have to send one request with all data.
Something like this:
Future<AboutUsContextModel> putAboutUsContent(
String title,
String context,
String subcontext,
PlatformFile imageId,
) async {
var request = http.MultipartRequest("PUT", Uri.parse(urlAddress + "/api/AboutUsContextModels/2"));
request.fields['title'] = title;
request.fields['context'] = context;
request.fields['subContext'] = subContext;
request.files.add(http.MultipartFile(
'imageFile',
imageId.readStream,
imageId.size,
filename: imageId.name,
));
final resp = await request.send();
if (resp.statusCode == 200) {
//If the server did return a 200 Created All green post
//then parse the JSON
return AboutUsContextModel.fromJson(jsonDecode(resp.body));
} else if (resp.statusCode == 400) {
throw Exception('Error code was 400. About Us Content Not Foun');
} else {
throw Exception('Nothing About Us Content created in Flutter');
}
}
Also, check this answer .

Error in WCF service value does not fall within the expected range

In one of our code, we are getting below error.
at System.Runtime.InteropServices.Marshal.ThrowExceptionForHRInternal(Int32 errorCode, IntPtr errorInfo)
at System.Web.Util.Misc.ThrowIfFailedHr(Int32 hresult)
at System.Web.Hosting.IIS7WorkerRequest.SetUnknownRequestHeader(String name, String value, Boolean replace)
at System.Web.HttpHeaderCollection.SetHeader(String name, String value, Boolean replace)
at System.Web.HttpHeaderCollection.Add(String name, String value)
Code is as below:
public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
{
string correlationId = newAuditTrail.GetCorrelationIdFromRequest(request).ToString();
string url = newAuditTrail.GetUrlFromRequest(request).ToString();
HttpContext.Current.Request.Headers.Add("CorrelatinId", correlationId);
HttpContext.Current.Request.Headers.Add("Url", url);
Error is thrown on line:
HttpContext.Current.Request.Headers.Add("CorrelatinId", correlationId);
I noticed operation contract of method, it is defined as oneway.
[OperationContract(IsOneWay=true)]
If you want to add http header in the http request, please refer to the below code segements.
public object BeforeSendRequest(ref System.ServiceModel.Channels.Message request, System.ServiceModel.IClientChannel channel)
{
HttpRequestMessageProperty httpRequestMessage;
object httpRequestMessageObject;
if (request.Properties.TryGetValue(HttpRequestMessageProperty.Name, out httpRequestMessageObject))
{
httpRequestMessage = httpRequestMessageObject as HttpRequestMessageProperty;
if (string.IsNullOrEmpty(httpRequestMessage.Headers[USER_AGENT_HTTP_HEADER]))
{
httpRequestMessage.Headers[USER_AGENT_HTTP_HEADER] = this.m_userAgent;
}
}
else
{
httpRequestMessage = new HttpRequestMessageProperty();
httpRequestMessage.Headers.Add(USER_AGENT_HTTP_HEADER, this.m_userAgent);
request.Properties.Add(HttpRequestMessageProperty.Name, httpRequestMessage);
}
return null;
}
We could also use WebOperationContext to add http header on the client-side.
Add Request header to WCF when using ConfigurationChannelFactory.CreateChannel
Please refer to the below discussion.
How to add a custom HTTP header to every WCF call?
Feel free to let me know if the problem still exists.

Cannot transfer file to S3 from ASP.Net Core Web API. Keep getting 'Access Denied'

I've been trying to figure this out for some time now and just cannot get it to work. I'm working on a web application where I'll have a user that needs to upload files to an S3 bucket and then other users will be able to view that content from the bucket. I've been trying to get the bucket upload to work with no avail. Here's the policies that I've set in IAM and S3 for my app/bucket:
Bucket:
{
"Version": "2012-10-17",
"Id": "Policy1488494182833",
"Statement": [
{
"Sid": "Stmt1488493308547",
"Effect": "Allow",
"Principal": {
"AWS": "arn:aws:iam::614222560511:user/NuRenAppUser"
},
"Action": "s3:*",
"Resource": [
"arn:aws:s3:::nu-ren-bucket",
"arn:aws:s3:::nu-ren-bucket/*"
]
}
]
}
IAM User:
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "FullAccessS3",
"Effect": "Allow",
"Action": "s3:*",
"Resource": [
"arn:aws:s3:::nu-ren-bucket"
]
}
]
}
I have my credentials in the .aws folder and the S3 client is picking them up just fine. The only issue with the credentials I'm not sure about is that there's a field when debugging that says "token" that's not being populated, but most of the documentation that I've seen just instructs to put in the two keys and the region, which I have set correctly. Here is my code:
ASP.Net Core 2.1 Web Api:
using Amazon.Runtime;
using Amazon.S3;
using Amazon.S3.Transfer;
using Amazon.S3.Model;
using Microsoft.AspNetCore.Http;
using NuRen.Services.Abstractions;
using NuRen.Services.Models;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading.Tasks;
namespace NuRen.Services.Repositories
{
public class VideoRepository : IVideoRepository
{
private IAmazonS3 _s3Client;
public VideoRepository(IAmazonS3 s3Client)
{
_s3Client = s3Client;
}
public async Task<Guid> SaveVideo(IFormFile file, Video newVideo)
{
Stream fileStream = file.OpenReadStream();
var request = new PutObjectRequest();
request.BucketName = "nu-ren-bucket";
request.Key = newVideo.ID.ToString();
request.InputStream = fileStream;
request.ContentType = file.ContentType;
request.CannedACL = S3CannedACL.PublicRead;
var response = await _s3Client.PutObjectAsync(request);
//var uploadrequest = new TransferUtilityUploadRequest()
//{
// InputStream = fileStream,
// Key = newVideo.ID.ToString(),
// BucketName = "nu-ren-bucket",
// CannedACL = S3CannedACL.PublicRead
//};
return newVideo.ID;
}
}
}
I know my model says video but I've just been testing with small files just to get it to work, so I know the size is not the issue. The code you see commented out is what I have tried before everything else and I keep getting the same issue:
Error:
An unhandled exception occurred while processing the request.
HttpErrorResponseException: Exception of type 'Amazon.Runtime.Internal.HttpErrorResponseException' was thrown.
Amazon.Runtime.HttpWebRequestMessage.GetResponseAsync(CancellationToken cancellationToken) in HttpRequestMessageFactory.cs, line 539
AmazonS3Exception: Access Denied
Amazon.Runtime.Internal.HttpErrorResponseExceptionHandler.HandleException(IExecutionContext executionContext, HttpErrorResponseException exception) in HttpErrorResponseExceptionHandler.cs, line 60
Stack Query Cookies Headers
HttpErrorResponseException: Exception of type 'Amazon.Runtime.Internal.HttpErrorResponseException' was thrown.
Amazon.Runtime.HttpWebRequestMessage.GetResponseAsync(CancellationToken cancellationToken) in HttpRequestMessageFactory.cs
Amazon.Runtime.Internal.HttpHandler<TRequestContent>.InvokeAsync<T>(IExecutionContext executionContext) in HttpHandler.cs
Amazon.Runtime.Internal.RedirectHandler.InvokeAsync<T>(IExecutionContext executionContext)
Amazon.Runtime.Internal.Unmarshaller.InvokeAsync<T>(IExecutionContext executionContext)
Amazon.S3.Internal.AmazonS3ResponseHandler.InvokeAsync<T>(IExecutionContext executionContext)
Amazon.Runtime.Internal.ErrorHandler.InvokeAsync<T>(IExecutionContext executionContext)
Show raw exception details
AmazonS3Exception: Access Denied
Amazon.Runtime.Internal.HttpErrorResponseExceptionHandler.HandleException(IExecutionContext executionContext, HttpErrorResponseException exception) in HttpErrorResponseExceptionHandler.cs
Amazon.Runtime.Internal.ErrorHandler.ProcessException(IExecutionContext executionContext, Exception exception) in ErrorHandler.cs
Amazon.Runtime.Internal.ErrorHandler.InvokeAsync<T>(IExecutionContext executionContext) in ErrorHandler.cs
Amazon.Runtime.Internal.CallbackHandler.InvokeAsync<T>(IExecutionContext executionContext)
Amazon.Runtime.Internal.EndpointDiscoveryHandler.InvokeAsync<T>(IExecutionContext executionContext)
Amazon.Runtime.Internal.EndpointDiscoveryHandler.InvokeAsync<T>(IExecutionContext executionContext) in EndpointDiscoveryHandler.cs
Amazon.Runtime.Internal.CredentialsRetriever.InvokeAsync<T>(IExecutionContext executionContext) in CredentialsRetriever.cs
Amazon.Runtime.Internal.RetryHandler.InvokeAsync<T>(IExecutionContext executionContext)
Amazon.Runtime.Internal.RetryHandler.InvokeAsync<T>(IExecutionContext executionContext) in RetryHandler.cs
Amazon.Runtime.Internal.CallbackHandler.InvokeAsync<T>(IExecutionContext executionContext)
Amazon.Runtime.Internal.CallbackHandler.InvokeAsync<T>(IExecutionContext executionContext)
Amazon.S3.Internal.AmazonS3ExceptionHandler.InvokeAsync<T>(IExecutionContext executionContext)
Amazon.Runtime.Internal.ErrorCallbackHandler.InvokeAsync<T>(IExecutionContext executionContext)
Amazon.Runtime.Internal.MetricsHandler.InvokeAsync<T>(IExecutionContext executionContext)
NuRen.Services.Repositories.VideoRepository.SaveVideo(IFormFile file, Video newVideo) in VideoRepository.cs
+
var response = await _s3Client.PutObjectAsync(request);
NuRen.Services.Services.VideoService.UploadVideo(IFormFile file) in VideoService.cs
+
return await _vr.SaveVideo(file, newVideo);
NuRenApp.Controllers.VideoController.UploadVideo(IFormFile file) in VideoController.cs
+
return await _vs.UploadVideo(file);
lambda_method(Closure , object )
Microsoft.Extensions.Internal.ObjectMethodExecutorAwaitable+Awaiter.GetResult()
Microsoft.AspNetCore.Mvc.Internal.ActionMethodExecutor+AwaitableObjectResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, object controller, object[] arguments)
System.Threading.Tasks.ValueTask<TResult>.get_Result()
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeActionMethodAsync()
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeNextActionFilterAsync()
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Rethrow(ActionExecutedContext context)
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeInnerFilterAsync()
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeNextResourceFilter()
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Rethrow(ResourceExecutedContext context)
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeFilterPipelineAsync()
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeAsync()
Microsoft.AspNetCore.Builder.RouterMiddleware.Invoke(HttpContext httpContext)
Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware.Invoke(HttpContext context)
Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore.MigrationsEndPointMiddleware.Invoke(HttpContext context)
Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore.DatabaseErrorPageMiddleware.Invoke(HttpContext httpContext)
Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore.DatabaseErrorPageMiddleware.Invoke(HttpContext httpContext)
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
I've tried different combinations of code, policies and keys and nothing has worked. Completely stuck at this point.

Duplicate type name within an assembly in Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware

I have .NET Core 1.1 API and i am handling the error in startup.cs as below. I am using Serilog
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IApplicationLifetime appLifetime, IRequestContext requestContext)
{
loggerFactory.AddSerilog();
// Ensure any buffered events are sent at shutdown
appLifetime.ApplicationStopped.Register(Log.CloseAndFlush);
var logger = loggerFactory.CreateLogger<Startup>();
app.UseExceptionHandler(
options =>
{
options.Run(
async context =>
{
context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
var ex = context.Features.Get<IExceptionHandlerFeature>();
if (ex != null)
{
var errmsg = "An unexpected error has occured in API.";
var logDetails = new
{
CorrelationId = requestContext.CorrelationId,
Message = errmsg
};
logger.LogError(1001, ex.Error, "{#LogDetails}", logDetails);
await context.Response.WriteAsync(errmsg).ConfigureAwait(false);
}
});
});
app.UseMvc();
logger.LogInformation("Application has started in environment {0}", env.EnvironmentName);
}
Most of the time when there is any exception, Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware logs the exception as expected however, sometimes i see the following exception in the logs
2018-09-21 18:36:01.670 +00:00 [Error] An unhandled exception has
occurred: Duplicate type name within an assembly.
System.ArgumentException: Duplicate type name within an assembly.
at System.Reflection.Emit.ModuleBuilder.CheckTypeNameConflict(String
strTypeName, Type enclosingType) at
System.Reflection.Emit.AssemblyBuilderData.CheckTypeNameConflict(String
strTypeName, TypeBuilder enclosingType) at
System.Reflection.Emit.TypeBuilder.Init(String fullname,
TypeAttributes attr, Type parent, Type[] interfaces, ModuleBuilder
module, PackingSize iPackingSize, Int32 iTypeSize, TypeBuilder
enclosingType) at
System.Reflection.Emit.ModuleBuilder.DefineType(String name,
TypeAttributes attr, Type parent, Type[] interfaces) at
Microsoft.Extensions.DiagnosticAdapter.Internal.ProxyAssembly.DefineType(String
name, TypeAttributes attributes, Type baseType, Type[] interfaces)
at
Microsoft.Extensions.DiagnosticAdapter.Internal.ProxyTypeEmitter.GenerateProxyTypeFromProperties(Type
sourceType, Type targetType, VerificationResult verificationResult)
at
Microsoft.Extensions.DiagnosticAdapter.Internal.ProxyTypeEmitter.VerifyProxySupport(ProxyBuilderContext
context, Tuple2 key) at
Microsoft.Extensions.DiagnosticAdapter.Internal.ProxyTypeEmitter.GetProxyType(ProxyTypeCache
cache, Type targetType, Type sourceType) at
Microsoft.Extensions.DiagnosticAdapter.Internal.ProxyFactory.CreateProxy[TProxy](Object
obj) at Proxy_Method_From_<>f__AnonymousType03_To_Void
OnBeforeAction(Microsoft.AspNetCore.Http.HttpContext,
IRouteData)(Object , Object , IProxyFactory ) at
Microsoft.Extensions.DiagnosticAdapter.DiagnosticSourceAdapter.Write(String
diagnosticName, Object parameters) at
Microsoft.Extensions.DiagnosticAdapter.DiagnosticSourceAdapter.System.IObserver>.OnNext(KeyValuePair`2
value) at System.Diagnostics.DiagnosticListener.Write(String
name, Object value) at
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.d__20.MoveNext()
--- End of stack trace from previous location where exception was thrown --- at
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task) at
Microsoft.AspNetCore.Builder.RouterMiddleware.d__4.MoveNext()
--- End of stack trace from previous location where exception was thrown --- at
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task) at
Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware.d__6.MoveNext()
So looks like Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware its selft throwing exception while logging
Update 1
I have the following references. Not sure which reference is causing this issue.
Microsoft.ApplicationInsights.AspNetCore is 2.0 however the only options available for this package are 1.0.* or 2.*.*. I don't see this package has 1.1.* available

calling FacebookClient.PostAsync from silverlight canvas app generates MethodAccessException

I am calling this from a silverlight app:
// docs at: http://developers.facebook.com/docs/reference/api/post
var client = new FacebookClient(_token);
dynamic parameters = new ExpandoObject();
parameters.message = title;
parameters.link = linkUrl;
parameters.picture = imageUrl;
parameters.name = name;
parameters.caption = promptTitle;
parameters.description = description;
parameters.privacy = new
{
value = "ALL_FRIENDS",
};
client.PostAsync("me/feed", parameters);
This generates the following error:
Attempt by security transparent method 'SimpleJson.Reflection.CacheResolver.CreateDynamicMethod(System.String, System.Type, System.Type[], System.Type)' to access security critical method 'System.Reflection.Emit.DynamicMethod..ctor(System.String, System.Type, System.Type[], System.Type, Boolean)' failed.
-- more: --
{System.MethodAccessException: Attempt by security transparent method 'SimpleJson.Reflection.CacheResolver.CreateDynamicMethod(System.String, System.Type, System.Type[], System.Type)' to access security critical method 'System.Reflection.Emit.DynamicMethod..ctor(System.String, System.Type, System.Type[], System.Type, Boolean)' failed.
at SimpleJson.Reflection.CacheResolver.CreateDynamicMethod(String name, Type returnType, Type[] parameterTypes, Type owner)
at SimpleJson.Reflection.CacheResolver.CreateGetHandler(PropertyInfo propertyInfo)
at SimpleJson.Reflection.CacheResolver.MemberMap..ctor(PropertyInfo propertyInfo)
at SimpleJson.PocoJsonSerializerStrategy.BuildMap(Type type, SafeDictionary2 memberMaps)
at SimpleJson.DataContractJsonSerializerStrategy.BuildMap(Type type, SafeDictionary2 map)
at SimpleJson.Reflection.CacheResolver.LoadMaps(Type type)
at SimpleJson.PocoJsonSerializerStrategy.TrySerializeUnknownTypes(Object input, Object& output)
at SimpleJson.PocoJsonSerializerStrategy.SerializeNonPrimitiveObject(Object input, Object& output)
at SimpleJson.SimpleJson.SerializeValue(IJsonSerializerStrategy jsonSerializerStrategy, Object value, StringBuilder builder)
at SimpleJson.SimpleJson.SerializeObject(Object json, IJsonSerializerStrategy jsonSerializerStrategy)
at SimpleJson.SimpleJson.SerializeObject(Object json)
at Facebook.JsonSerializer.SimpleJsonSerializer.SerializeObject(Object obj)
at Facebook.FacebookUtils.ToJsonQueryString(IDictionary2 dictionary)
at Facebook.FacebookClient.BuildRequestData(Uri uri, IDictionary2 parameters, HttpMethod httpMethod, Uri& requestUrl, String& contentType)
at Facebook.FacebookClient.BuildRequestData(String path, IDictionary2 parameters, HttpMethod method, Uri& requestUrl, String& contentType)
at Facebook.FacebookClient.ApiAsync(String path, IDictionary2 parameters, HttpMethod httpMethod, Object userToken)
at Facebook.FacebookClient.PostAsync(String path, IDictionary2 parameters, Object userToken)
at Facebook.FacebookClient.PostAsync(String path, IDictionary2 parameters)
at CallSite.Target(Closure , CallSite , FacebookClient , String , Object )
at System.Dynamic.UpdateDelegates.UpdateAndExecuteVoid3[T0,T1,T2](CallSite site, T0 arg0, T1 arg1, T2 arg2)
was a bug with the sdk at that time. has been fixed since.