I am currently stuck with reading form data. Below is my controller code.
using System.Net;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
using Rehub.Models;
using IHostingEnvironment = Microsoft.AspNetCore.Hosting.IHostingEnvironment;
namespace Rehub_v1._0.Areas.Admin.Controllers
{
public class TestController : Controller
{
private IHostingEnvironment Environment;
public TestController()
{
}
[HttpPost]
public async Task<HttpResponseMessage> Post()
{
string path = Path.Combine(this.Environment.WebRootPath, "~/App_Data");
var provider = new MultipartFormDataStreamProvider(path);
await Request.Content.ReadAsMultipartAsync(provider);
var email = new SendGridEmail
{
Dkim = provider.FormData.GetValues("dkim").FirstOrDefault(),
To = provider.FormData.GetValues("to").FirstOrDefault(),
Html = provider.FormData.GetValues("html").FirstOrDefault(),
From = provider.FormData.GetValues("from").FirstOrDefault(),
Text = provider.FormData.GetValues("text").FirstOrDefault(),
SenderIp = provider.FormData.GetValues("sender_ip").FirstOrDefault(),
Envelope = provider.FormData.GetValues("envelope").FirstOrDefault(),
Attachments = int.Parse(provider.FormData.GetValues("attachments").FirstOrDefault()),
Subject = provider.FormData.GetValues("subject").FirstOrDefault(),
Charsets = provider.FormData.GetValues("charsets").FirstOrDefault(),
Spf = provider.FormData.GetValues("spf").FirstOrDefault()
};
// The email is now stored in the email variable
return new HttpResponseMessage(HttpStatusCode.OK);
}
}
}
I get the error on await Request.Content.ReadAsMultipartAsync(provider):
"CS1061 C# ‘HttpRequest’ does not contain a definition for ‘Content’ and no accessible extension method ‘Content’ accepting a first argument of type ‘HttpRequest’ could be found"
Related
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using pdrake.Models;
namespace pdrake.Controllers
{
public class MovieApiController : Controller
{
private const string baseUrl = "https://api.themoviedb.org/3/discover/movie?api_key=my_key";
public List<Movie> Movies { get; set; }
public async Task<AcceptedResult> GetMovies()
{
using (var httpClient = new HttpClient())
{
httpClient.BaseAddress = new Uri(baseUrl);
httpClient.DefaultRequestHeaders.Accept.Clear();
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
}
Movies = JsonConvert.DeserializeObject<List<Movie>>(Json(baseUrl));
return View(Movies);
}
}
}
I've been struggling all day trying to figure out how to transfer the Json from baseUrl to the list Movies which can be looped through with a foreach loop.
Change your using block to the following,
using (var httpClient = new HttpClient())
{
var response = await httpClient.GetAsync(baseUrl);
string data = await response.Content.ReadAsStringAsync();
return View(JsonConvert.DeserializeObject<List<Movie>>(data));
}
This will call the baseUrl along with receiving the text / content from the response. once you have the data, you can deserialize that to your List<Movie> object and return it as a View.
I have an error in this code. I deserialize a JSON file and stored that data in the database now I want to show that data from my database.
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Web.Helpers;
using System.Web.Mvc;
using ReadingFromDb.Dto;
namespace ReadingFromDb.Controller
{
public class StudentController
{
[HttpGet]
[AllowAnonymous]
public async Task<JsonResult> GetStudents()
{
using (var context = new UNIEntities1())
{
var query = #"Select ";
var dbQuery = context.Database.SqlQuery<StudentDto>(query);
var list = await dbQuery.ToListAsync();
return Json(list,JsonRequestBehavior.AllowGet);
}
}
}
}
Error is:
JSON can not be used like method.
What should I do?
Your contoller must be extend the base class Controller in which the Json() virtual method is available:
public class StudentController : Controller
{
// your code
}
To resolve this error you can try as below
public class StudentController : Controller
{
// your code
}
[HttpGet]
[AllowAnonymous]
public async Task<JsonResult> GetStudents()
{
using (var context = new UNIEntities1())
{
var list = await context.StudentDto.ToListAsync();
return Json(list,JsonRequestBehavior.AllowGet);
}
}
What you need to do is to extend your StudentCotroller with Controller then put your code under that.
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Web.Helpers;
using System.Web.Mvc;
using ReadingFromDb.Dto;
namespace ReadingFromDb.Controller
{
public class StudentController:Controller
{
[HttpGet]
[AllowAnonymous]
public async Task<JsonResult> GetStudents()
{
using (var context = new UNIEntities1())
{
var query = #"Select ";
var dbQuery = context.Database.SqlQuery<StudentDto>(query);
var list = await dbQuery.ToListAsync();
return Json(list,JsonRequestBehavior.AllowGet);
}
}
}
}
I am receiving the following error: The name 'Ok' does not exist in the current context.
How would I resolve this issue in my Controller API? Return Ok is already embedded in the controller.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using System.Net.Http;
using Newtonsoft.Json;
using WeatherTest.Models;
namespace WeatherChecker.Controllers
{
public class WeatherData
{
[HttpGet("[action]/{city}")]
public async Task<IActionResult> City(string city)
{
using (var client = new HttpClient())
{
try
{
client.BaseAddress = new Uri("http://api.openweathermap.org");
var response = await client.GetAsync($"/data/2.5/weather?q={city}&appid=YOUR_API_KEY_HERE&units=metric");
response.EnsureSuccessStatusCode();
var stringResult = await response.Content.ReadAsStringAsync();
var rawWeather = JsonConvert.DeserializeObject<OpenWeatherResponse>(stringResult);
// Error Here: ** The name 'Ok' does not exist in the current context **
return Ok(new
{
Temp = rawWeather.Main.Temp,
Summary = string.Join(",", rawWeather.Weather.Select(x => x.Main)),
City = rawWeather.Name
});
}
catch (HttpRequestException httpRequestException)
{
// Error Here: The name 'BadRequest' does not exist in the current context
return BadRequest($"Error getting weather from OpenWeather: {httpRequestException.Message}");
}
}
}
}
}
With Attribute routing feature, aspnet support POCO controller. It allow to use any class as controller. But you will we lose all utilities and helpers provided by framework base classes.
The class Controller inherite from ControllerBase and add view support. In your case, ControllerBase is enough.
public class WeatherData : ControllerBase // <-
{
// ...
}
I'm new to .NET and I'm making a web api with asp.net. I'm trying to post a file to AWS S3 using the AWS .Net SDK.
It works but not if I try to read the fileName and send that as the key. It only works if I hardcode the key to a string (whereas I always want the key to be the same as the filename of the uploaded file).
When I try to read the filename from the file the error I'm getting is "Your socket connection to the server was not read from or written to within the timeout period. Idle connections will be closed."
So far I'm just using Postman to POST the files. I set the "Content-Type" header to multipart/form-data but exactly the same thing happens if I set it to application/x-www-form-urlencoded.
This is my UploadController:
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Linq;
using BlogApi.Models;
using System.Web;
using awsTestUpload;
using Amazon.S3.Model;
using Microsoft.AspNetCore.Http;
namespace BlogApi.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class S3UploadController : ControllerBase
{
public S3UploadController()
{
}
[HttpGet]
public ListObjectsResponse GetAll()
{
var uploader = new AmazonUploader();
return uploader.ListingObjectsAsync().Result;
}
[HttpPost]
public PutObjectResponse MyFileUpload()
{
var request = HttpContext.Request;
var fileStream = request.Body;
var contentLength = request.ContentLength;
string filePath = request.Form.Files.First().FileName;
var length = contentLength.HasValue ? (long)contentLength : 0;
var uploader = new AmazonUploader();
return uploader.sendMyFileToS3(fileStream, filePath, length).Result;
}
}
}
and the Uploader class looks like this:
using System;
using System.Diagnostics;
using System.Net;
using System.Threading.Tasks;
using System.IO;
using Amazon;
using Amazon.S3;
using Amazon.S3.Model;
using Amazon.S3.Transfer;
using Microsoft.Extensions.Configuration;
namespace awsTestUpload
{
public class AmazonUploader
{
public AmazonUploader() {
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json");
Configuration = builder.Build();
client = new AmazonS3Client(Configuration["aws:AWS_KEY"],
Configuration["aws:AWS_SECRET"], bucketRegion);
}
private IAmazonS3 client;
public static IConfiguration Configuration { get; set; }
private const string bucketName = "my-bucket-name";
private static readonly RegionEndpoint bucketRegion = RegionEndpoint.EUWest2;
public async Task<ListObjectsResponse> ListingObjectsAsync()
{
ListObjectsRequest request = new ListObjectsRequest
{
BucketName = bucketName
};
return await client.ListObjectsAsync(request);
}
public async Task<PutObjectResponse> sendMyFileToS3(System.IO.Stream inputStream, string fileNameInS3, long contentLength = 0)
{
PutObjectRequest request = new PutObjectRequest
{
BucketName = bucketName,
Key = fileNameInS3,
InputStream = inputStream
};
request.Headers.ContentLength = contentLength;
return await client.PutObjectAsync(request);
}
}
}
When I debug and set a breakpoint, the value of filePath is a string matching the file name ( as I expect) but the upload is timing out. if I just set filePath to be a hardcoded string (ie replace string filePath = request.Form.Files.First().FileName; with string filePath = "foo.png";) it works fine.
Can anyone see why there's a difference?
I'm pretty new to rest API and restsharp so I need some help. I need to get a magento version 2.2.3 admin token but I keep getting a bad request. I've followed this tutorial: https://www.youtube.com/watch?v=2sdGuC7IUAI&t=343s. But I'm ending up with a bad request. When I check the statuscode using a the breakpoints from the tutorial I get: NotFound.
My main goal is to get the categories I have in Magento. But to get that I need an admin token. I already have a bearer acces code etc.
I would really appreciate your help.
my code so far:
magento.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using RestSharp;
using Newtonsoft.Json;
namespace MagentoTest
{
public class magento
{
private RestClient Client { get; set; }
private string Token { get; set; }
public magento(string magentoUrl)
{
Client = new RestClient(magentoUrl);
}
public magento(string magentoUrl,string token)
{
Client = new RestClient(magentoUrl);
Token = token;
}
public string GetAdminToken(string userName, string passWord)
{
var request = CreateRequest("/rest/V1/integration/admin/token", Method.POST);
var user = new Credentials();
user.username = userName;
user.password = passWord;
string Json = JsonConvert.SerializeObject(user, Formatting.Indented);
request.AddParameter("aplication/json", Json, ParameterType.RequestBody);
var response = Client.Execute(request);
if (response.StatusCode == System.Net.HttpStatusCode.OK)
{
return response.Content;
}
else
{
return "";
}
}
private RestRequest CreateRequest(string endPoint, Method method)
{
var request = new RestRequest(endPoint, method);
request.RequestFormat = DataFormat.Json;
return request;
}
}
}
Credentials:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MagentoTest
{
public class Credentials
{
public string username { get; set; }
public string password { get; set; }
}
}
(Client)
Program.cs
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MagentoTest;
namespace Client
{
class Program
{
static void Main(string[] args)
{
GetToken("blabla", "blabla");
}
static void GetToken(string userName, string passWord)
{
var m2 = new magento("http://beta.topprice24.com");
string token = m2.GetAdminToken(userName, passWord);
}
}
}
It looks, relative URL needs to be changed as "/rest/default/V1/integration/admin/token"
(https://devdocs.magento.com/guides/v2.1/get-started/order-tutorial/order-admin-token.html).
I have simplified the above code and you can easily get the token.
Keep your Credentials class as it is and change your main program as below
Modified Code:(Program.cs)
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Client
{
class Program
{
static void Main(string[] args)
{
//Base URL needs to be Specified
String host = "http://beta.topprice24.com";
//Relative URL needs to be Specified
String endpoint = "/rest/default/V1/integration/admin/token";
RestClient _restClient = new RestClient(host);
var request = new RestRequest(endpoint, Method.POST);
//Initialize Credentials Property
var userRequest = new Credentials{username="blabla",password="blabla"};
var inputJson = JsonConvert.SerializeObject(userRequest);
//Request Header
request.AddHeader("Content-Type", "application/json");
request.AddHeader("Accept", "application/json");
//Request Body
request.AddParameter("application/json", inputJson, ParameterType.RequestBody);
var response = _restClient.Execute(request);
var token=response.Content;
}
}
}