I have created Web API using Oracle Database in C# ASP.NET MVC and ADO.NET Entity Model and everything works fine.
And right now, I need to create a another project which will call this API.
I create this because this Web API is a part of application and it will connect to another application.
I create a new MVC project and in my controller
public ActionResult GetAkontas()
{
IEnumerable<AkontasViewModel> akontas = null;
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost:57285/api/");
var responseTask = client.GetAsync("akontas");
responseTask.Wait();
var result = responseTask.Result;
if (result.IsSuccessStatusCode)
{
var readTask = GetReadTask(result);
readTask.Wait();
akontas = readTask.Result;
}
else
{
//Error response received
akontas = Enumerable.Empty<AkontasViewModel>();
ModelState.AddModelError(string.Empty, "Server error try after some time.");
}
}
return View(akontas);
}
Here is the problem that I dont know how to call it API controller, do I need to have connection to server since I work with Oracle database ?
I create Model but not so sure do I need it however
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace AkontasMVCWebApi.Models
{
public class AkontasViewModel
{
public string A_KONTO { get; set; }
public string NAZIV { get; set; }
public string SIFRA_RAD { get; set; }
public string OPSTINA { get; set; }
public string MB { get; set; }
public string ULICA { get; set; }
public string BROJ { get; set; }
public string PBROJ { get; set; }
public string MJESTO { get; set; }
public string PORESKI { get; set; }
public string TRANSAKCIJ { get; set; }
public string INTERNET { get; set; }
public string EMAIL { get; set; }
public string KONTAKT { get; set; }
public string TELEFON { get; set; }
public string FAKS { get; set; }
public DateTime? DAT_UNOS { get; set; }
public string PDVMB { get; set; }
public string VRSTA_KLIJENTA { get; set; }
public string DRZAVA { get; set; }
}
}
This is my first time to work with Oracle database and ADO.NET Entities and not so sure how to do this, create a Project which will call(use) my API
UPDATE
Here is my Web API project
Controller
using System.Linq;
using System.Web.Http;
using System.Web.Http.Description;
namespace AkontasWebApi.Controllers
{
public class AkontasController : ApiController
{
//Ovo je objekat kojem se pristupa kroz bazu
public AkontasEntities db = new AkontasEntities();
// GET: api/Akontas
//Ovo je funkcija koja vraca Listu<> svih AKONTASA iz baze ne vezano po ID-u
[HttpGet]
[Route("api/Akontas")]
public IQueryable<AKONTA> GetAKONTAS()
{
return db.AKONTAS;
}
// GET: api/Akontas/5 -> ovo je routing tacnije putanja kako se koristi ova funkcija
//Ovo je funkcija koja vraca AKONTAS po ID-u
[HttpGet]
[ResponseType(typeof(AKONTA))]
public IHttpActionResult GetAKONTA(string id)
{
AKONTA aKONTA = db.AKONTAS.Find(id);
if (aKONTA == null)
{
return BadRequest("Ne postoji A_KONTO pod tim rednim brojem");
}
return Ok(aKONTA);
}
}
}
Index View
<br /><br />
<form>
<div class="form-group">
<label>A_KONTO</label>
<input type="text" class="form-control" aria-describedby="AKONTO BROJ" placeholder="Unesite broj AKONOTO" id='AkontasId'>
</div>
<div class="form-group">
<a class="btn btn-primary" id="aKonto" onClick='aKontoSubmit()'>Provjeri</a>
</div>
</form>
<script>
function aKontoSubmit() {
$.ajax({
type: "GET",
URL: "/api/Akontas/GetAKONTA",
data: { id: $('#AkontasId').val() },
contentType: "data/xml; charset=utf-8",
success: function (result) {
window.location.href = "http://localhost:57285/api/Akontas/" + $('#AkontasId').val();
},
error: function () {
alert("Ne postoji AKONTO pod tim rednim brojem");
}
});
}
</script>
I can recommend some stuff to look out for:
1) Try using https in http://localhost:57285/api/. I've had a similar problem but not on IIS, I was using kestrel web server.
2) Try this after setting the base address and before GetAsync():
client.DefaultRequestHeaders.Clear();
//Define request data format
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
Related
I am sending data to HTTP post API. But everytime I try to call the API, I get error code: 400, Bad request message.
Here is my API code:
[Route("InsUpPlayer")]
[HttpPost]
public async Task<object> InsUpPlayer([FromForm] Players player)
{
try
{
//Some code here
}
catch (Exception e)
{
throw new Exception(e.Message);
}
}
And my repository code:
public async Task<string> PlayerInsUpPost(Player player1)
{
var SendResponse = "false";
try
{
var RequestUrl = baseUrl + "Master/InsUpPlayer";
var httpClient = new HttpClient();
httpClient.BaseAddress = new Uri(RequestUrl);
using (var player = new MultipartFormDataContent())
{
if (player1.ProfileImageFile != null)
{
string objimgFileBase64 = "";
ByteArrayContent fileContent;
using (var ms = new MemoryStream())
{
player1.ProfileImageFile.CopyTo(ms);
var fileBytes = ms.ToArray();
objimgFileBase64 = Convert.ToBase64String(fileBytes);
}
byte[] bytes = Convert.FromBase64String(objimgFileBase64);
fileContent = new ByteArrayContent(bytes);
player.Add(fileContent, "ProfileImageFile", string.Format("{0}", player1.ProfileImageFile.FileName));
}
if (player1.DetailImageFile != null)
{
string objimgFileBase64 = "";
ByteArrayContent fileContent;
using (var ms = new MemoryStream())
{
player1.DetailImageFile.CopyTo(ms);
var fileBytes = ms.ToArray();
objimgFileBase64 = Convert.ToBase64String(fileBytes);
}
byte[] bytes = Convert.FromBase64String(objimgFileBase64);
fileContent = new ByteArrayContent(bytes);
player.Add(fileContent, "DetailImageFile", string.Format("{0}", player1.DetailImageFile.FileName));
}
player.Add(new StringContent(player1.playerId.ToString()), "playerId");
player.Add(new StringContent(player1.FirstName), "FirstName");
player.Add(new StringContent(player1.LastName), "LastName");
player.Add(new StringContent(player1.DOB.ToString()), "DOB");
player.Add(new StringContent(player1.Nationality.ToString()), "Nationality");
player.Add(new StringContent(player1.BirthState.ToString()), "BirthState");
player.Add(new StringContent(player1.JerseyNo.ToString()), "JerseyNo");
player.Add(new StringContent(player1.Postion.ToString()), "Postion");
player.Add(new StringContent(player1.Biography), "Biography");
player.Add(new StringContent(player1.isActive.ToString()), "isActive");
player.Add(new StringContent(player1.isPublish.ToString()), "isPublish");
player.Add(new StringContent(player1.UserType.ToString()), "UserType");
HttpResponseMessage objResponse = await httpClient.PostAsync(RequestUrl, player);
if (objResponse.IsSuccessStatusCode && (int)objResponse.StatusCode == 200)
{
var serResponse = objResponse.ContentAsType<ResultModel>();
//SendResponse = serResponse.result;
SendResponse = "true";
}
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Exception Occured");
throw;
}
return SendResponse;
}
The Player class is like this:
public class Player
{
public long playerId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime DOB { get; set; }
public int Nationality { get; set; }
public int BirthState { get; set; }
public int JerseyNo { get; set; }
public int Postion { get; set; }
public string Biography { get; set; }
public bool isActive { get; set; }
public bool isPublish { get; set; }
public int UserType { get; set; }
public IFormFile ProfileImageFile { get; set; }
public IFormFile DetailImageFile { get; set; }
public string ProfileImage { get; set; }
public string DetailImage { get; set; }
}
Update: Here is my JQuery code: The DOB here is correct, but I realized just now that it is not getting passed correctly to the controller.
$("#PublishPlayer").click(function () {
debugger;
var value = $('#CreatePlayerForm').valid();
var url = '/Admin/PlayerInsUpPost';
var day = $('#Day').val();
var month = $('#Month').val();
var year = $('#Year').val();
var DOB = new Date(year, month, day);
var fdata = new FormData();
fdata.append("playerId", $('#playerId').val());
fdata.append("FirstName", $('#FirstName').val());
fdata.append("LastName", $('#LastName').val());
fdata.append("DOB", DOB);
fdata.append("Nationality", $('#Nationality').val());
fdata.append("BirthState", $('#BirthState').val());
fdata.append("JerseyNo", $('#JerseyNo').val());
fdata.append("Position", $('#Position').val());
fdata.append("Biography", $('#Biography').val());
fdata.append('ProfileImageFile', $('#ProfileImageFile')[0].files[0]);
fdata.append('DetailImageFile', $('#ProfileImageFile')[0].files[0]);
if (value == true) {
$.ajax({
url: url,
datatype: "json",
accept: {
javascript: 'application/javascript'
},
type: "POST",
cache: false,
processData: false,
contentType: false,
data: fdata,
success: function (result) {
if (result == "true") {
alert('Player added successfully.');
window.location.href = "/Admin/PlayerList";
} else if (result == "false") {
alert('Failed to update, please try later.');
}
},
error: function () {
alert('Something went wrong');
}
});
}
else {
//$('.playeradd').removeClass('show');
//$('.playeradd').addClass('hide');
return false;
}
//event.stopPropagation();
});
The DOB in JQuery before calling Ajax is : Wed Sep 12 2001 00:00:00 GMT+0530 (India Standard Time) {}
When passed to controller it is: {01-01-0001 12:00:AM}
If I comment DOB in API and in the frontend, everything works fine. But I need to send DOB to API and I can't change the datatype of DOB in API. How do I fix this error?
When passing the data into the ajax request convert it to ISO string. Dotnet understands that. So do something like this:
fdata.append("DOB", DOB.toISOString());
I suppose it is some problem with ASP.NET deserialization of DateTime (I'm not sure tho). I have run into similar problem of sending dates before and my solution was instead of sending DateTime struct, I send number of ticks (which you can get from DateTime object) as long variable.
DateTime BOD = DateTime.Now; // You may fill your DateTime object with your own data
long BODticks = BOD.Ticks;
And then on the server side you can easily recreate date time like this:
DateTime myDate = new DateTime(BODticks);
And then in order to use it you can modify your player class as follows:
public class Player
{
public long playerId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public long DOBTicks { get; set; }
public DateTime DOB { get => new DateTime(DOBTicks); set => DOBTicks = value.Ticks; }
public int Nationality { get; set; }
public int BirthState { get; set; }
public int JerseyNo { get; set; }
public int Postion { get; set; }
public string Biography { get; set; }
public bool isActive { get; set; }
public bool isPublish { get; set; }
public int UserType { get; set; }
public IFormFile ProfileImageFile { get; set; }
public IFormFile DetailImageFile { get; set; }
public string ProfileImage { get; set; }
public string DetailImage { get; set; }
}
I'm sure someone could find a better solution though and that's assuming this one actually works and I understood your problem right.
The new serializer in .net core > 3.0 is strict when parsing date formats (note that the default has changed from newtonsoft json). They have to be in ISO8601 format, i.e. YYYY-MM-DD. If you are passing something that isn't in ISO8601 forms you have to write a custom formatter.
public class DateTimeJsonConverter : JsonConverter<DateTime>
{
public override DateTime Read(
ref Utf8JsonReader reader,
Type typeToConvert,
JsonSerializerOptions options) =>
DateTime.ParseExact(reader.GetString(),
"<YOUR FORMAT HERE>", CultureInfo.InvariantCulture);
public override void Write(
Utf8JsonWriter writer,
DateTime dateTimeValue,
JsonSerializerOptions options) =>
writer.WriteStringValue(dateTimeValue.ToString(
"<YOUR FORMAT HERE>", CultureInfo.InvariantCulture));
}
The code above is an example of a custom formatter.
Read further details here (https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-converters-how-to#sample-basic-converter) in how to create a custom formatter for your input.
This is my first ask. I have 2 models for 1 view. I built the code but i have a problem. data comes null from view to controller.
Models:
Mom model:
public class BildirimOlusturViewModel
{
public BildirimOlusturModel bildirimOlusturModel { get; set; }
public TagBoxViewModel tagBoxViewModel { get; set; }
}
Child models:
public class BildirimOlusturModel
{
[Required(ErrorMessage = "Lütfen bildirim tipi seçiniz")]
public string BildirimTipi { get; set; }
[Required(ErrorMessage = "Lütfen alıcı tipi seçiniz")]
public string AliciTipi { get; set; }
[Required(ErrorMessage = "Lütfen alıcı seçiniz")]
public string Alicilar { get; set; }
[Required(ErrorMessage = "Lütfen bir başlık giriniz")]
public string Baslik { get; set; }
[Required(ErrorMessage = "Mesaj boş olamaz")]
public string Mesaj { get; set; }
}
public class TagBoxViewModel
{
public List<string> Items { get; set; }
}
View:
#model xyz.Web.Notifications.Models.BildirimOlusturViewModel
<form method="post" asp-controller="Bildirim" asp-action="BildirimOlustur">
...
#(Html.DevExtreme().SelectBoxFor(s => s.bildirimOlusturModel.AliciTipi)
.Placeholder("Alıcı Tipi...")
.DataSource(new List<SelectListItem> {
new SelectListItem
{
Text = "Personel",
Value = "personel".ToString()
},
new SelectListItem
{
Text = "Müşteri",
Value = "musteri".ToString()
}})
.ValueExpr("Value").DisplayExpr("Text")
.OnValueChanged("alicitipi_changed")
.ID("slcAliciTipi")
)
</div>
<div class="col-md-8">
#(Html.DevExtreme().TagBoxFor(x => x.bildirimOlusturModel.Alicilar)
.Items(Model.tagBoxViewModel.Items)
.SearchEnabled(true)
.Placeholder("Alıcı...")
.ID("TagBoxAlici")
)
#(Html.DevExtreme().TextBoxFor(x => x.bildirimOlusturModel.Baslik)
.Placeholder("Başlık...")
)
<input type="text" id="Mesaj" asp-for="bildirimOlusturModel.Mesaj" name="bildirimOlusturModel.Mesaj" id="bildirimOlusturModel.Mesaj"/>
#(Html.DevExtreme().Button()
.Text("Submit")
.Type(ButtonType.Default)
.StylingMode(ButtonStylingMode.Contained)
.Width(120)
.UseSubmitBehavior(true)
)
</form>
Controller:
[HttpPost]
public IActionResult BildirimOlustur(BildirimOlusturModel model)
{
string sAlicilar = model.Alicilar;
string sAliciTipi = model.AliciTipi;
string sBaslik = model.Baslik;
string sBildirimTipi = model.BildirimTipi;
string sMesaj = model.Mesaj;
}
Submit button sends me inside the post method but not sends the model. My variables coming null. Thank you for help.
Try adding a [FromBody] attribute before your argument.
public IActionResult BildirimOlustur([Frombody] BildirimOlusturModel model)
I solved the problem. controller was waiting for the wrong parameter.
[HttpPost]
public IActionResult BildirimOlustur(BildirimOlusturViewModel model)
{
BildirimOlusturModel mdl = new BildirimOlusturModel();
mdl = model.bildirimOlusturModel;
string sAlicilar = mdl.Alicilar;
}
I've created a CSV parser using the most recommended nuget I could find on here, CSVReader. I think my code is almost there its just posting the file to the controller actionmethod I can't quite find enough on. I get the error:
System.IO.FileNotFoundException: 'Could not find file 'C:\Program Files (x86)\IIS Express\System.Web.HttpPostedFileWrapper'.'
Controller action method:
[HttpPost]
public ActionResult CreateBulk(HttpPostedFileBase attachmentcsv)
{
if (ModelState.IsValid)
{
using (CsvReader csv = new CsvReader(new StreamReader(attachmentcsv.ToString()), true))
{
csv.Configuration.HasHeaderRecord = true;
var records = csv.GetRecords<Client>().ToList();
foreach (var item in records)
{
String Strip = item.homePage.Replace("https://www.", "").Replace("http://www.", "").Replace("https://", "").Replace("http://", "").Replace("www.", "");
string[] URLtests = { "https://www." + Strip, "http://www." + Strip, "https://" + Strip, "http://" + Strip };
string[] Metric = MajesticFunctions.MajesticChecker(URLtests);
var userId = User.Identity.GetUserId();
var UserTableID = db.UserTables.Where(c => c.ApplicationUserId == userId).First().ID;
var newclient = new Client { clientN = item.clientN, homePage = Metric[0], clientEmail = item.clientEmail, contName = item.contName.First().ToString().ToUpper() + item.contName.Substring(1), monthlyQuota = item.monthlyQuota, TrustFlow = Int32.Parse(Metric[1]), CitationFlow = Int32.Parse(Metric[2]), RI = Int32.Parse(Metric[3]), MJTopicsID = item.MJTopicsID, UserTableID = UserTableID };
ViewBag.newdomain = newclient;
db.Clients.Add(newclient);
db.SaveChanges();
return RedirectToAction("Index");
}
}
}
return RedirectToAction("Index");
View upload button:
#using (Html.BeginForm("CreateBulk", "Clients", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div class="form-group">
<label for="attachment">Select a Csv File</label>
<label class="btn btn-default btn-file">
<input type="file" name="attachmentcsv" id="attachmentcsv" hidden>
</label>
</div>
<button type="submit" class="btn btn-primary">Upload</button>
}
Client Model:
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace Linkofy.Models
{
public class Client
{
public int ID { get; set; }
[Required]
[Display(Name = "Client")]
public string clientN { get; set; }
[Display(Name = "Website")]
public string homePage{ get; set; }
[EmailAddress]
[Display(Name = "Contact Email")]
public string clientEmail { get; set; }
[Display(Name = "Contact Name")]
public string contName { get; set; }
[Display(Name = "Monthly")]
public int monthlyQuota { get; set; }
[Display(Name = "TF")]
public int TrustFlow { get; set; }
[Display(Name = "CF")]
public int CitationFlow { get; set; }
[Display(Name = "RIPs")]
public int RI { get; set; }
public int? MJTopicsID { get; set; }
public virtual MJTopics MJTopics { get; set; }
public int UserTableID { get; set; }
public virtual UserTable UserTable { get; set; }
public virtual ICollection<Link> Links { get; set; }
public virtual ICollection<Status> Statuss { get; set; }
}
}
You should check out: File upload in MVC
But looking into your code there are a few things that I wanted to point out:
Isolating the attachmentcsv.ToString() line it appears that this returns the type of System.Web.HttpPostedFileWrapper, this is why this string is being appended onto the file location.
I believe you may be looking for the attachmentcsv.FileName, which according to documentation of the type (https://msdn.microsoft.com/en-us/library/system.web.httppostedfilewrapper(v=vs.110).aspx)
Gets the fully qualified name of the file on the client
I'm not sure if you are using the framework or the core version of ASP, but I believe in the framework version of ASP the "correct" way of accessing upload files (as indicated in the linked answer) is to go through the Request object:
Request.Files.
https://msdn.microsoft.com/en-us/library/system.web.httprequest.files(v=vs.110).aspx
In the core version of ASP you can have a IFileForm as indicated here:
https://learn.microsoft.com/en-us/aspnet/core/mvc/models/file-uploads
[HttpPost("UploadFiles")]
public async Task<IActionResult> Post(List<IFormFile> files)
{
long size = files.Sum(f => f.Length);
// full path to file in temp location
var filePath = Path.GetTempFileName();
foreach (var formFile in files)
{
if (formFile.Length > 0)
{
using (var stream = new FileStream(filePath, FileMode.Create))
{
await formFile.CopyToAsync(stream);
}
}
}
// process uploaded files
// Don't rely on or trust the FileName property without validation.
return Ok(new { count = files.Count, size, filePath});
}
Hope this helps
I am running into a problem. I have my database properly configured and image is saving in database properly but dont know how to construct url for the image saved in database as i have to supply it to the knockout view model for binding.
public JsonResult GetPosts()
{
var ret = (from post in db.Posts.ToList()
orderby post.PostedDate descending
select new
{
Message = post.Message,
PostedBy = post.PostedBy,
PostedByName = post.ApplicationUser.UserName,
// having problem at this line dont know how to construct url at this line as i have to supply url
// (String type to the PostedByAvatar)
PostedByAvatar = db.Files.SingleOrDefault(s => s.ApplicationUserId == post.PostedBy),
PostedDate = post.PostedDate,
PostId = post.PostId,
}).AsEnumerable();
return Json(ret, JsonRequestBehavior.AllowGet);
}
this is the knockout function--------
function Post(data) {
var self = this;
data = data || {};
self.PostId = data.PostId;
self.Message = ko.observable(data.Message || "");
self.PostedBy = data.PostedBy || "";
self.PostedByName = data.PostedByName || "";
self.PostedDate = getTimeAgo(data.PostedDate);
self.PostedByAvatar = data.PostedByAvatar || "";
self.error = ko.observable();
self.PostComments = ko.observableArray();
and this is the view model to get the existing post, comment etc with image from the database-----
function viewModel() {
var self = this;
self.posts = ko.observableArray();
self.newMessage = ko.observable();
self.error = ko.observable();
self.loadPosts = function () {
// to load existing posts
$.ajax({
url: postApiUrl1,
datatype: "json",
contentType: "application/json",
cache: false,
type: 'Get'
})
and on my view page, this the container box to load the image with post-----
<ul id="msgHolder" data-bind="foreach: posts">
<li class="postHolder">
<img data-bind="attr: { src: PostedByAvatar }">
<p><a data-bind="text: PostedByName"></a>: <span data-bind=" html: Message"></span></p>
Now, the model class which saves the image in database is something like this.It has ApplicationUserId as foreign key pointing to ApplicationUserClass---
public class File
{
[Key]
public int FileId { get; set; }
[StringLength(255)]
public string FileName { get; set; }
[StringLength(100)]
public string ContentType { get; set; }
public byte[] Content { get; set; }
public FileType FileType { get; set; }
public int ApplicationUserId { get; set; }
public virtual ApplicationUser ApplicationUser { get; set; }
}
and ApplicationUserClass is something like this---
public class ApplicationUser : IdentityUser<int, CustomUserLogin, CustomUserRole, CustomUserClaim>
{
public ApplicationUser()
{
this.Posts = new HashSet<Post>();
this.Files = new HashSet<File>();
}
public virtual ICollection<File> Files { get; set; }
public virtual ICollection<Post> Posts { get; set; }
This is the image saved in database.Now, i want to know how to construct url for the image saved in the database as i have to supply it to the view model in string form. or there is any approach better than this.
This is my Post class which have many to one relationship with ApplicationUser class and foreign key is PostedBy pointing the ApplicationUser Class----
public class Post
{
public Post()
{
this.PostComments = new HashSet<PostComment>();
}
[Key]
public int PostId { get; set; }
public string Message { get; set; }
public int? PostedBy { get; set; }
public System.DateTime PostedDate { get; set; }
public virtual ICollection<PostComment> PostComments { get; set; }
public virtual ApplicationUser ApplicationUser { get; set; }
}
Although it is possible to pass a Base64 string as the src of the <img>, I think the most sensible way would be to not return the actual bytes from the Ajax call but rather create a url that will request the image bytes from the server.
First, add the required Action that will serve the image data:
[HttpGet]
public FileResult GetFileData(int fileId)
{
var file = db.Files.Single(x => x.FileId == fileId);
return File(file.Content, file.ContentType);
}
Now, change your GetPosts action to return url in the PostedByAvatar property:
public JsonResult GetPosts()
{
var ret = (from post in db.Posts.ToList()
orderby post.PostedDate descending)
select new
{
Message = post.Message,
PostedBy = post.PostedBy,
PostedByName = post.ApplicationUser.UserName,
PostedByAvatar = _GenerateAvatarUrlForUser(post.PostedBy),
PostedDate = post.PostedDate,
PostId = post.PostId,
});
return Json(ret, JsonRequestBehavior.AllowGet);
}
private string _GenerateAvatarUrlForUser(int? userId)
{
if (!user.HasValue)
return null;
var avatarImage = db.Files.SingleOrDefault(s => s.ApplicationUserId == userId);
if (avatarImage != null)
return Url.Action("GetFileData", new { fileId = avatarImage.FileId });
return null;
}
I have encountered a problem when trying to call my web api with a post request, a empty array is returned.
My method is:
// POST: Api/v1/transaction/
[HttpPost]
public HttpResponseMessage Post(string user)
{
var userId = new Guid(user);
var transactions = new Collection<TransactionDataTransferObject>();
try
{
var seller = _databaseContext.Sellers.Single(s => s.Id == userId);
var sellerMedias = _databaseContext.Medias.Where(m => m.TakenBy.Id == seller.Id);
foreach (var sellerMedia in sellerMedias)
{
var allLogsForMedia = _databaseContext.Logs.Where(l => l.ObjectReferenceId == sellerMedia.Id);
foreach (var logMedia in allLogsForMedia)
{
var transaction = new TransactionDataTransferObject
{
Date = logMedia.DateTimeInUtc,
Amount = sellerMedia.PriceInSek,
MediaName = sellerMedia.FileName,
UserName = seller.FirstName + " " + seller.LastName
};
transactions.Add(transaction);
}
}
}
catch (Exception exception)
{
return Request.CreateErrorResponse(HttpStatusCode.NotFound, exception);
}
return Request.CreateResponse(HttpStatusCode.OK, transactions);
}
When I debug transactions variable, I see two objects in the collection.
My response to postman is
[
{},
{}
]
What have I done wrong? Where is my data which is sent?
Ok, after some hours of slaming my head in the table i found out that I used
[DataContract] as filter on the ViewModel,TransactionDataTransferObject.
Like this:
[DataContract]
public class TransactionDataTransferObject
{
[Display(Name = "Date")]
public DateTime Date { get; set; }
public string MediaName { get; set; }
public Guid MediaId { get; set; }
public string UserName { get; set; }
public Guid UserId { get; set; }
[Display(Name = "Description")]
public string Discriminator { get; set; }
[Display(Name = "Amount")]
public decimal Amount { get; set; }
}
Which was wrong in this case...
Thanks for reading!