How to consume .Net webservice in angular post method? - asp.net

how to call post method in angular 5 and ionic 3.
My angular code is:
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
let body= {
records:
this.records
};
this.http.post('http://localhost:13799/HealthPotliWebService.asmx/getsingleproductdetails',
"{body2:" + JSON.stringify(body) + "}",options)
.map(res=>res.json())
.subscribe(data=>{
console.log(data);
});
}
this is my webservice class
my class is like this :
public class body2
{
public List<records> records { get; set; }
}
public class records
{
public int CategoryID { get; set; }
public string CategoryName { get; set; }
public string Description { get; set; }
}
webservice code :
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string getsingleproductdetails(body2 body2)
{
// some code here
return new JavaScriptSerializer().Serialize(resources);
}
Return type of my webservice is:
<string xmlns="http://tempuri.org/">
{"error_msg":"Success","status":"0","medicinename":"CROCIN","description":"\u003cdiv style=\u0027text-align:justify;\u0027\u003e\u003cu\u003e\u003cb\u003eParacetamol\u003c/b\u003e\u003c/u\u003e-\u003cu\u003e125mg\u003c/u\u003e\u003cbr/\u003e\u003cbr/\u003e\u003c/div\u003e","lstComments":[],"rateValue":0,"potliMoney":0,"offer":null}
</string>

Related

Debugger Stops while Parsing Rest API response HttpClient, Xamarin Forms

I am trying to parse response from ASP.NET Core Web API. I am able to parse the response JSON into C# object successfully but app crashes without throwing any error when the parsed C# object is returned to the ViewModel.
in ViewModel
ApiResponse response = await _apiManager.GetAsync<ApiResponse>("authentication/GetUserById/1");
Response JSON:
{
"result": {
"id": 1,
"userType": 1,
"firstName": “FirstName”,
"middleName": null,
"lastName": “LastName”,
},
"httpStatusCode": 200,
"httpStatusDescription": "200OkResponse",
"success": true,
"message": "hello"
}
HttpClient GetAsync() method:
public async Task<TResult> GetAsync<TResult>(string endpoint)
{
HttpResponseMessage httpResponse = _httpClient.GetAsync(endpoint).GetAwaiter().GetResult();
httpResponse.EnsureSuccessStatusCode();
TResult t = default(TResult);
if (httpResponse.IsSuccessStatusCode)
{
string serialized = await httpResponse.Content.ReadAsStringAsync();
t = JsonConvert.DeserializeObject<TResult>(serialized);
}
return t;
}
App crashes (debugger stops without any error) at "return t" statement. Here, _httpClient is a singleton object of HttpClient using DI.
TResult model is ApiResponse object
public class User
{
[JsonProperty("id")]
public int UserId { get; set; }
[JsonProperty("userType")]
public int UserType { get; set; }
[JsonProperty("firstName")]
public string FirstName { get; set; }
[JsonProperty("middleName")]
public string MiddleName { get; set; }
[JsonProperty("lastName")]
public string LastName { get; set; }
}
public abstract class ResponseBase
{
[JsonProperty("httpStatusCode")]
public int HttpStatusCode { get; protected set; }
[JsonProperty("httpStatusDescription")]
public string HttpStatusDescription { get; protected set; }
[JsonProperty("success")]
public bool Success { get; protected set; }
[JsonProperty("message")]
public string Message { get; protected set; }
}
public class ApiResponse : ResponseBase
{
[JsonProperty("result")]
public User Result { get; set; } = new User();
}
There are two issues:
1. when the following statement executes, app crashes and debugger stops without throwing any error.
HttpResponseMessage httpResponse = await _httpClient.GetAsync(endpoint).ConfigureAwait(false);
But when GetAsync() is called with .GetAwaiter().GetResult(), network call is placed successfully. I do not understand why ConfigureAwait(false) fails.
HttpResponseMessage httpResponse = _httpClient.GetAsync(endpoint).GetAwaiter().GetResult();
why the following call fails and app crashes? How can I return parsed C# object to the calling code?
return JsonConvert.DeserializeObject(serialized);
Please advise.
Try this
try
{
var result = await httpClient.GetAsync(endpoint);
var response = await result.Content.ReadAsStringAsync();
data = JsonConvert.DeserializeObject<TResult>(response);
}
catch (Exception exp)
{
Console.Write(exp.InnerMessage);
}
Make sure that you have installed Newtonsoft.Json

asp.net web api list of list pass into json ajax

I have web api controller where I try to do something like this:
public IHttpActionResult Get()
{
var Rooms = db.Rooms.Select(r => new {
Id = r.Id,
Name = r.Name,
ChairNum = r.СhairNum,
Requests = r.Requests.ToList()
}).ToList();
return Ok(new { results = Rooms });
}
In Model I have this:
public partial class Room
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Room()
{
this.Requests = new HashSet<Request>();
}
public int Id { get; set; }
public string Name { get; set; }
public int СhairNum { get; set; }
public bool IsProjector { get; set; }
public bool IsBoard { get; set; }
public string Description { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Request> Requests { get; set; }
}
I tried to pass this data in service. But I have serialization error, when I call http://localhost:99999/api/Rest.
<ExceptionMessage>
The "ObjectContent`1" type could not serialize the response text for the content type "application / json; charset = utf-8".
</ ExceptionMessage>
What is the best way to pass the data like in model into json?
It helped to put in WebApiConfig:
var json = config.Formatters.JsonFormatter;
json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
config.Formatters.Remove(config.Formatters.XmlFormatter);

Properties of class parameter are always null in Asp.Net Web Api

In my web api controller there is an action method like below
[HttpPost]
[EnableCors(origins: "*", headers: "*", methods: "*", exposedHeaders: "X-Custom-Header")]
public IReportOutput InsuranceHandlingFiles([FromBody]CaseCountsInputData caseCountsInputData)
{
}
Parameter class of this action is
[Serializable]
public class CaseCountsInputData
{
public string MainTitle { get; set; }
public string YearTitle { get; set; }
public string InsurerFileCountTitle { get; set; }
public List<FileCount> FileCounts { get; set; }
public int InsurerTotalCount { get; set; }
public int GrandTotal { get; set; }
public string TotalTitle { get; set; }
public string GrandTotalTitle { get; set; }
}
[Serializable]
public class FileCount
{
public string year { get; set; }
public int InsurerFilesCount { get; set; }
}
I call this API method for testing purposes as follows. My action is called this way and my json object is binded to CaseCountsInputData class but all parameters are null. Can you help me exactly where I made the mistake?
$("#btnExport")
.click(function() {
var reportData = GetReportData();
console.log(JSON.stringify(reportData));
$.ajax({
type: "POST",
dataType: "json",
data: JSON.stringify(reportData),
contentType: "application/json",
url: "http://localhost:50773/api/export/insurancehandlingfiles",
success: function(data) {
var DocumentBody = data.Data;
var FileName = data.FileName;
dataURItoBlob(DocumentBody, FileName);
},
error: function(error,as,asd) {
jsonValue = jQuery.parseJSON(error.responseText);
alert("error" + error.responseText);
}
});
});
});
function GetReportData() {
var reportModel = {
CaseCountsInputData: {
MainTitle: "Dosya Sayısı",
YearTitle: "Yıl",
InsurerFileCountTitle: "Sigortacı Dosya Sayısı",
TotalTitle: "Toplam",
GrandTotalTitle: "Genel Toplam",
InsurerTotalCount: 1,
GrandTotal: 3,
FileCounts: []
}
}
var caseCounts =[];
caseCounts.push({
"year": 2014,
"InsurerFilesCount": 1
});
caseCounts.push({
"year": 2015,
"InsurerFilesCount": 4
});
for (var i = 0; i < caseCounts.length; i++) {
reportModel.CaseCountsInputData.FileCounts.push(caseCounts[i]);
}
return reportModel;
}

How can we pass the more than One class objects to WCF REST API?

I have a WCF REST API method which accepts two class objects (RequestFormat = JSON ) as inputs . I know the process of passing the single object. Can anyone help me the process of passing more than one object as inputs in WCF Rest API method.
You need to set message body style as wrapped: WebMessageBodyStyle.Wrapped.
Here is an example:
Data model:
public class ServiceResult
{
public string ResultCode { get; set; }
}
public class User
{
public string UserId { get; set; }
public string Name { get; set; }
public string Surename { get; set; }
}
public class Account
{
public string AccNumber { get; set; }
public bool IsActive { get; set; }
}
Service interface method:
[OperationContract]
[WebInvoke(UriTemplate = "user/details", Method = "POST", RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped)]
ServiceResult Details(User user, string key, Account account);
Code to request data:
const string json = #"{
""user"":
{
""UserId"":""12"",
""Name"":""Bogdan"",
""Surename"":""Perecotypole""
},
""key"": ""12345"",
""account"":
{
""AccNumber"":""ED12"",
""IsActive"":""true""
}
}";
Uri uri= new Uri("http://localhost/user/details");
var wc = new WebClient();
wc.Headers["Content-Type"] = "application/json";
var resJson = wc.UploadString(uri, "POST", json);

HTTP POST to Many to Many relation using ASP.NET Web API

I am new to ASP.net (and programming in general) and I'm having trouble building a Web API. More specifically I need help in these two areas:
How to configure my DOCcontroller to post a new document (DOC table).
How to make the actual ajax post -- I am having trouble passing the EXT_GUID parameter. As it stands I get an error when I try to post. "Can't bind multiple parameters (doc and parentOwner) to the request's content."
Essentially this is for a simple document management system. I want Get/Post documents (DOC) by having the user supply an GUID from an external database (the EXT_GUID field) as a filter/parameter. Each document can have multiple EXT_GUIDs and each EXT_GUID can have multiple Documents (DOC). You can assume that the EXT_GUID fields we be populated prior to the http post.
This is the DOCcontroller code
//POST api/DOC
public HttpResponseMessage PostDOC(DOC doc, List<string> parentOwners)
{
if (ModelState.IsValid)
{
var parents = db.BIMs.Where(bx => parentOwners.Contains(bx.EXT_GUID));
foreach (var p in parents)
doc.Owners.Add(p);
db.DOCs.Add(doc);
db.SaveChanges();
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, doc);
response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = doc.Id }));
return response;
}
else
{
return Request.CreateResponse(HttpStatusCode.BadRequest);
}
}
This is my model setup -- EntityFramework codefirst stuff
public class EXT
{
public int Id { get; set; }
public string EXT_GUID { get; set; }
public int ProjectID { get; set; }
public virtual ICollection<DOC> DOCs { get; set; }
}
public class DOC
{
public int Id { get; set; }
public int ProjectID { get; set; }
public string Subject { get; set; }
public string Link { get; set; }
public virtual ICollection<EXT> EXTs { get; set; }
}
This is more Storage Model...
public StoreDBContext() : base("name=StoreDBContext")
{
}
public DbSet<EXT> EXTs { get; set; }
public DbSet<DOC> DOCs { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
//Set FLUENT API config for many to many here
modelBuilder.Entity<EXT>()
.HasMany(a => a.DOCs)
.WithMany()
.Map(x =>
{
x.MapLeftKey("EXT_Id");
x.MapRightKey("DOC_Id");
x.ToTable("EXTsDOCs");
});
}
AJAX Code
function AddDOC() {
var parentOwner = "{\"" + $('#txtaddEXT').val() + "\"}";
jQuery.support.cors = true;
var DOC = {
ProjectId: ProjectID,
Subject: $('#txtaddDOCSubject').val(),
Link: $('#txtaddDOCLink').val(),
parentOwner: parentOwner
};
$.ajax({
url: "http://localhost:54171/api/DOC/",
type: 'POST',
data: JSON.stringify(DOC),
contentType: "application/json;charset=utf-8",
success: function (data) {
WriteResponse(data);
},
error: function (x, y, z) {
alert(x + '\n' + y + '\n' + z);
}
});
}
What you receive from the client and what you will save in the database is two different things.
Your doc object is ok:
var DOC = {
ProjectId: ProjectID,
Subject: $('#txtaddDOCSubject').val(),
Link: $('#txtaddDOCLink').val(),
parentOwner: parentOwner
};
Now you need to change the server logic. Make a model like this:
public class DocReceivedModel
{
public int ProjectID { get; set; }
public string Subject { get; set; }
public string Link { get; set; }
public List<string> parentOwner { get; set; }
}
Then your PostDOC method will be:
public HttpResponseMessage PostDOC(DocReceivedModel docReceived)
{
if (ModelState.IsValid)
{
Doc newDoc = new Doc();
newDoc.ProjectID = docReceived.ProjectID
newDoc.Subject = docReceived.Subject
newDoc.Link = docReceived.Link
var parents = db.BIMs.Where(bx => docReceived.parentOwners.Contains(bx.EXT_GUID));
foreach (var p in parents)
newDoc.Owners.Add(p);
// I not see in your model Owners, maybe this is EXTs but I suppose you catch the idea
db.DOCs.Add(newDoc);
db.SaveChanges();
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, newDoc);
response.Headers.Location = new Uri(Url.Link("DefaultApi", new {id = newDoc.Id}));
return response;
}
else
{
return Request.CreateResponse(HttpStatusCode.BadRequest);
}
}

Resources