Exception in Json response when Submitting to webapi from WP8 - c#

I'm having issue when i try to send data to Web api which gives an exception
HRESULT E_FAIL has been returned from a call to a COM component
System.Net.Browser.ClientHttpWebRequest.InternalEndGetResponse(IAsyncResult asyncResult) at System.Net.Browser.ClientHttpWebRequest.<>c__DisplayClasse.b__d(Object sendState) at System.Net.Browser.AsyncHelper.<>c__DisplayClass1.b__0(Object sendState)
at response
HttpResponseMessage response = await client.GetAsync(String.Format(url, Isexist, jsontalleyHeader.ToString(), jsontalleydetail.ToString()));
Wp8 method
public async Task<string> POSTtalleyDetails(bool Isexist, int count)
{
string val = "";
if ((Isexist == false))//first time Load started--need headerNo
{
try
{
using (HttpClient client = new HttpClient())
{
var valjsontalleyHeader = listRtnTalleySheetHeader;
var jsontalleyHeader = Newtonsoft.Json.JsonConvert.SerializeObject(valjsontalleyHeader);
var valtalleydetail = listRtnTalleySheetDetail;
var jsontalleydetail = Newtonsoft.Json.JsonConvert.SerializeObject(valtalleydetail);
client.BaseAddress = new Uri("http://service:Port");
var url = "api/config/InsertTalleydetail?Isexist={0}&talleyheaderlist={1}&talleydetails={2}";
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = await client.GetAsync(String.Format(url, Isexist, jsontalleyHeader.ToString(), jsontalleydetail.ToString()));
if (response.IsSuccessStatusCode)
{
val = "Ok";
}
else
{
val = "No";
}
}
return val;
}
catch (Exception ex)
{
ex.ToString(); return val = "No";
}
//
}
}
where jsontalleydetail will be
[{"_Isedited":true,"_CreatedBy":"tc1","_visitID":"VISIT0001783","_Remark":"","_Syncable":true,"_ID":"VISIT0001783","_ItemName":"Aeroplane (M) Flour 50Kg","_TalleySheetDetailNo":"39.0D39.053000","_TalleySheetHeaderNo":"T2H1.033000","_ItemMasterId":33,"_WareHouseId":2,"_ManufacturedDate":"2018-09-25T00:00:00+05:30","_LoadingTypeId":7,"_LoadingDate":"2018-09-25T16:51:53.7504239+05:30","_ConfirmedHatti":7,"_HattiId":1,"_HattiQty":5,"_HattiWeight":0},{"_Isedited":true,"_CreatedBy":"tc1","_visitID":"VISIT0001783","_Remark":"","_Syncable":true,"_ID":"VISIT0001783","_ItemName":"Aeroplane (M) Flour 50Kg","_TalleySheetDetailNo":"40.0D40.053000","_TalleySheetHeaderNo":"T2H1.033000","_ItemMasterId":33,"_WareHouseId":2,"_ManufacturedDate":"2018-09-25T00:00:00+05:30","_LoadingTypeId":7,"_LoadingDate":"2018-09-25T16:51:53.8672939+05:30","_ConfirmedHatti":7,"_HattiId":2,"_HattiQty":1,"_HattiWeight":0},{"_Isedited":true,"_CreatedBy":"tc1","_visitID":"VISIT0001783","_Remark":"","_Syncable":true,"_ID":"VISIT0001783","_ItemName":"Aeroplane (M) Flour 50Kg","_TalleySheetDetailNo":"41.0D41.054000","_TalleySheetHeaderNo":"T2H1.033000","_ItemMasterId":33,"_WareHouseId":2,"_ManufacturedDate":"2018-09-25T00:00:00+05:30","_LoadingTypeId":7,"_LoadingDate":"2018-09-25T16:51:54.0238698+05:30","_ConfirmedHatti":7,"_HattiId":3,"_HattiQty":2,"_HattiWeight":0},{"_Isedited":true,"_CreatedBy":"tc1","_visitID":"VISIT0001783","_Remark":"","_Syncable":true,"_ID":"VISIT0001783","_ItemName":"Aeroplane (M) Flour 50Kg","_TalleySheetDetailNo":"42.0D42.054000","_TalleySheetHeaderNo":"T2H1.033000","_ItemMasterId":33,"_WareHouseId":2,"_ManufacturedDate":"2018-09-25T00:00:00+05:30","_LoadingTypeId":7,"_LoadingDate":"2018-09-25T16:51:54.1564773+05:30","_ConfirmedHatti":7,"_HattiId":4,"_HattiQty":5,"_HattiWeight":0},{"_Isedited":true,"_CreatedBy":"tc1","_visitID":"VISIT0001783","_Remark":"","_Syncable":true,"_ID":"VISIT0001783","_ItemName":"Aeroplane (M) Flour 50Kg","_TalleySheetDetailNo":"43.0D43.054000","_TalleySheetHeaderNo":"T2H1.033000","_ItemMasterId":33,"_WareHouseId":2,"_ManufacturedDate":"2018-09-25T00:00:00+05:30","_LoadingTypeId":7,"_LoadingDate":"2018-09-25T16:51:54.2542986+05:30","_ConfirmedHatti":7,"_HattiId":5,"_HattiQty":2,"_HattiWeight":0},{"_Isedited":true,"_CreatedBy":"tc1","_visitID":"VISIT0001783","_Remark":"","_Syncable":true,"_ID":"VISIT0001783","_ItemName":"Aeroplane (M) Flour 50Kg","_TalleySheetDetailNo":"44.0D44.054000","_TalleySheetHeaderNo":"T2H1.033000","_ItemMasterId":33,"_WareHouseId":2,"_ManufacturedDate":"2018-09-25T00:00:00+05:30","_LoadingTypeId":7,"_LoadingDate":"2018-09-25T16:51:54.3582527+05:30","_ConfirmedHatti":7,"_HattiId":6,"_HattiQty":1,"_HattiWeight":0},{"_Isedited":true,"_CreatedBy":"tc1","_visitID":"VISIT0001783","_Remark":"","_Syncable":true,"_ID":"VISIT0001783","_ItemName":"Aeroplane (M) Flour 50Kg","_TalleySheetDetailNo":"45.0D45.054000","_TalleySheetHeaderNo":"T2H1.033000","_ItemMasterId":33,"_WareHouseId":2,"_ManufacturedDate":"2018-09-25T00:00:00+05:30","_LoadingTypeId":7,"_LoadingDate":"2018-09-25T16:51:54.4742785+05:30","_ConfirmedHatti":7,"_HattiId":7,"_HattiQty":2,"_HattiWeight":0}]
and
jsontalleyHeader will be
[{"_Remark":"","_TsStartTime":"2018-09-25T16:51:54.4742785+05:30","_TsEndDatetime":"0001-01-01T00:00:00","_VisitID":"VISIT0001783","_Approxweight":18.0,"_WHId":2,"_TalleySheetHeaderNo":"T2H1.033000","_Isedited":false,"_CreatedBy":null,"_visitID":null,"_Syncable":false,"_ID":null,"_ItemName":null,"_TalleySheetDetailNo":null,"_ItemMasterId":0,"_WareHouseId":0,"_ManufacturedDate":"0001-01-01T00:00:00","_LoadingTypeId":null,"_LoadingDate":"0001-01-01T00:00:00","_ConfirmedHatti":null,"_HattiId":null,"_HattiQty":null,"_HattiWeight":0}]
my web api method is
[HttpPost]
public HttpResponseMessage InsertTalleydetail([FromBody]List<clsTalleySheetHeader> talleyheaderlist, List<clsTalleySheetDetail>talleydetails)
{
return todoService.InsertTalleydetail(talleyheaderlist, talleydetails);
//base.BuildSuccessResult(HttpStatusCode.OK, StartTimeDetails);
}
I beleive this is because due to the data Load, because its work fine with 2 to 3 jsontalleydetail .
if could someone could advise me with regard to this , it will be a big help.
I was answered to similar question https://stackoverflow.com/questions/52202989/json-value-doesnt-assign-to-the-list-httppost

Related

Trying to understand Async/Await but seem to get deadlock c#

I have an async method, and from within that method I call another Async method.
In the second method I call an API. I know that my API request is correct, so it has something to do with the async/await.
Am I creating a deadlock? If so where? And how to fix it?
public async Task<AmountInvoicedModel> CreatePaymentsAndSendAsEmail(InvoiceRequestModel model, bool calculate)
{
....
await CreateQRCodes("testMsg");
....
}
public async Task CreateQRCodes(string ocrNmbr)
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("https://mpc.getswish.net/qrg-swish/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
var json = new
{
payee = new
{
value = "01234567890",
editable = false
},
amount = new
{
value = 100,
editable = false
},
message = new
{
value = $"{ocrNmbr}",
editable = false
},
format = "jpg",
size = 300
};
try
{
HttpResponseMessage response = await client.PostAsJsonAsync(
"api/v1/prefilled", json);
var result = await response.Content.ReadAsStreamAsync();
}
catch (Exception ex)
{
throw;
}
}
UPDATE: I had to put await on the "CalculateInvoice" method too. So now it doesnt deadlock anymore, it moves on - but without giving me a response
[HttpPost]
[Route("calculateInvoice")]
public async Task<IHttpActionResult> CalculateInvoice([FromBody] InvoiceRequestModel model)
{
model.EmailAddress = AccountHelper.GetLoggedInUsername();
var result = await _paymentHandler.CreatePaymentsAndSendAsEmail(model, true);
if (result == null)
return Conflict();
return Ok(result);
}
I had to put await on the CalculateInvoice method for it to move on.
[HttpPost]
[Route("calculateInvoice")]
public async Task<IHttpActionResult> CalculateInvoice([FromBody] InvoiceRequestModel model)
{
model.EmailAddress = AccountHelper.GetLoggedInUsername();
var result = await _paymentHandler.CreatePaymentsAndSendAsEmail(model, true);
if (result == null)
return Conflict();
return Ok(result);
}

Connection reset issue in .net core api call (net::ERR_CONNECTION_RESET 200 (OK))

I have a .net core API service which is called from a angular client project.
When a user request a status of his payment, we will make call to this service api and this service will then call a payment gateway service to fetch the status of payment and the output result will return to the user.
When i try to integrate this i am facing this below error.
net::ERR_CONNECTION_RESET 200 (OK)
core.js:5967 ERROR Unknown Error
This above issue is not showing when i try to hit the service after putting one breakpoint. Its also returning the result.
This is how entire flow works
Client side call performs by user
this.dataservice.postFeed(method, JSON.stringify(this.initsearch)).subscribe(result => {
var response = result.body["data"];
console.log(response);
});
Server side code looks like
[HttpPost]
public async Task<IActionResult> Post([FromBody] ObjectModel searchValue)
{
ApiResponse<string> response = new ApiResponse<string>();
IBaseResult<string> result = await _adlerBo.GetPaymentStatus(searchValue);
response.Success = result.success;
response.Data = result.Data;
return Ok(response);
}
In BusinessObject.cs
public async Task<IBaseResult<string>> GetPaymentStatus(PaymentSearchModel requestModel){
string apiResponse = await PaymentStatusCheckUsingAPI(requestModel.orderid);
return apiResponse ;
}
private async Task<string> PaymentStatusCheckUsingAPI(string orderNumber)
{
string message = await PostPaymentRequestToGateway(statusApiUrl, authQueryUrlParam);
NameValueCollection param = await GetResponseMap(message);
string status = "";
string encResJson = "";
if (param != null && param.Count == 2)
{
for (int i = 0; i < param.Count; i++)
{
if ("status".Equals(param.Keys[i]))
{
status = param[i];
}
if ("enc_response".Equals(param.Keys[i]))
{
encResJson = param[i];
}
}
if (!"".Equals(status) && status.Equals("0"))
{
resJson = crypto.Decrypt(encResJson, workingKey);
}
else if (!"".Equals(status) && status.Equals("1"))
{
Console.WriteLine("failure response: " + encResJson);
}
}
return resJson;
}
private async Task<string> PostPaymentRequestToGateway(string queryUrl, string urlParam)
{
string message = "";
try
{
StreamWriter myWriter = null;// it will open a http connection with provided url
WebRequest objRequest = WebRequest.Create(queryUrl);//send data using objxmlhttp object
objRequest.Method = "POST";
//objRequest.ContentLength = TranRequest.Length;
objRequest.ContentType = "application/x-www-form-urlencoded";//to set content type
myWriter = new System.IO.StreamWriter(objRequest.GetRequestStream());
myWriter.Write(urlParam);//send data
myWriter.Close();//closed the myWriter object
// Getting Response
System.Net.HttpWebResponse objResponse = (System.Net.HttpWebResponse)objRequest.GetResponse();//receive the responce from objxmlhttp object
using (System.IO.StreamReader sr = new System.IO.StreamReader(objResponse.GetResponseStream()))
{
message = await sr.ReadToEndAsync();
//Response.Write(message);
}
}
catch (Exception exception)
{
Console.Write("Exception occured while connection." + exception);
}
return message;
}
private async Task<NameValueCollection> GetResponseMap(string message)
{
//await Task.Delay(2000); I did this with no Luck
NameValueCollection Params = new NameValueCollection();
if (message != null || !"".Equals(message))
{
string[] segments = message.Split('&');
foreach (string seg in segments)
{
string[] parts = seg.Split('=');
if (parts.Length > 0)
{
string Key = parts[0].Trim();
string Value = parts[1].Trim();
Params.Add(Key, Value);
}
}
}
return await Task.FromResult(Params);
}
Any idea how to fix this? Why its working when i put breakpoint and not otherwise.
Am i doing correct asynchronous implimentsion in my api?

Passing a message back with response code via class

I am using a web api but I want to be able to pass back a message with my response but I am using this method outside in a class how would one do that in the example of the following.
public HttpStatusCode CreateInvoice(string PumpName,string customerCode, double fuelQty, double price)
{
HttpStatusCode retval = new HttpStatusCode();
SAPbobsCOM.Documents oInvoice = company.GetBusinessObject(BoObjectTypes.oInvoices);
oInvoice.DocDate = DateTime.Now;
oInvoice.CardCode = customerCode;
oInvoice.Lines.ItemCode = "DSL";
oInvoice.Lines.Quantity = fuelQty;
oInvoice.Lines.LineTotal = price;
oInvoice.Lines.Add();
int addInvoice = oInvoice.Add();
if (addInvoice == 0)
{
retval = HttpStatusCode.OK;
}
if (addInvoice < 0)
{
string errorDescription = company.GetLastErrorDescription();
retval = HttpStatusCode.NotModified;
}
return retval;
}
I want to be able to pass back this line as part of the response message I no how to do it in the controller but this function is outside in a class. As there I dont have access to the request object?
string errorDescription = company.GetLastErrorDescription();
Edit 2
Ok so I created the function with httprequest message but i am not seeing the result in the header its showing me status 200 ok for invoice created but not the message.
public HttpResponseMessage CreateInvoice(string PumpName,string customerCode, double fuelQty, double price,string FuelType)
{
HttpResponseMessage retval = new HttpResponseMessage();
SAPbobsCOM.Documents oInvoice = company.GetBusinessObject(BoObjectTypes.oInvoices);
HttpRequestMessage Errordescription = new HttpRequestMessage() ;
oInvoice.DocDate = DateTime.Now;
oInvoice.CardCode = customerCode;
oInvoice.Lines.ItemCode = FuelType;
oInvoice.Lines.Quantity = fuelQty;
oInvoice.Lines.LineTotal = price;
oInvoice.Lines.Add();
int addInvoice = oInvoice.Add();
if (addInvoice == 0)
{
retval.StatusCode = HttpStatusCode.OK;
retval.RequestMessage=new HttpRequestMessage(HttpMethod.Post, "Invoice has been created!");
}
if (addInvoice < 0)
{
retval.StatusCode = HttpStatusCode.NotAcceptable;
retval.RequestMessage = new HttpRequestMessage(HttpMethod.Post,string.Format("Invoice was not created {0} sap code error {1}!", company.GetLastErrorDescription(),addInvoice));
}
HttpResponseMessage response = retval;
return response;
}
Here is how I consume the message in my API Controller.
public HttpResponseMessage Post(string PumpName, string FuelTagNumber,
double FuelQty, double FuelValue, string FuelType, string TransactionDate, string TransActionDate, string systemgroup1, string systemgroup2, string systemgroup3, string systemgroup4)
{
HttpResponseMessage retVal = new HttpResponseMessage();
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, "value");
int connect = _boneAPi.Connect();
if (connect == 0)
{
string CustomerCode = _boneAPi.GetCustomerCodeByVechicleTag(FuelTagNumber);
HttpResponseMessage _invoiceStatusCode = _boneAPi.CreateInvoice(PumpName, CustomerCode, FuelQty, FuelValue,FuelType);
retVal = _invoiceStatusCode;
_boneAPi.ImportTransactionToTable("", CustomerCode, TransactionDate, TransactionDate, systemgroup1, systemgroup3, FuelTagNumber, systemgroup2, systemgroup4, FuelQty.ToString(), FuelValue.ToString(), FuelType, "1");
}
return retVal;
}
To show post man result
Edit 2
To Show others how I solved it.
public HttpResponseMessage CreateInvoice(string PumpName, string customerCode, double fuelQty, double price, string FuelType)
{
HttpResponseMessage retval = new HttpResponseMessage();
SAPbobsCOM.Documents oInvoice = company.GetBusinessObject(BoObjectTypes.oInvoices);
HttpRequestMessage Errordescription = new HttpRequestMessage();
oInvoice.DocDate = DateTime.Now;
oInvoice.CardCode = customerCode;
oInvoice.Lines.ItemCode = FuelType;
oInvoice.Lines.Quantity = fuelQty;
oInvoice.Lines.LineTotal = price;
oInvoice.Lines.Add();
int addInvoice = oInvoice.Add();
if (addInvoice == 0)
{
retval.StatusCode = HttpStatusCode.OK;
retval.RequestMessage = new HttpRequestMessage(HttpMethod.Post, "");
retval.Content = new StringContent("Invoice has been created!");
}
if (addInvoice < 0)
{
retval.StatusCode = HttpStatusCode.NotAcceptable;
retval.Content = new StringContent(string.Format("Invoice was not created {0} sap code error {1}!", company.GetLastErrorDescription(), addInvoice));
}
HttpResponseMessage response = retval;
return response;
}
How about making the return a Tuple
If you are using c# 7 it would look like this:
public (HttpStatusCode code, string description) CreateInvoice(string PumpName, string customerCode, double fuelQty, double price)
{
HttpStatusCode retval = new HttpStatusCode();
string errorDescription = string.Empty;
SAPbobsCOM.Documents oInvoice = company.GetBusinessObject(BoObjectTypes.oInvoices);
oInvoice.DocDate = DateTime.Now;
oInvoice.CardCode = customerCode;
oInvoice.Lines.ItemCode = "DSL";
oInvoice.Lines.Quantity = fuelQty;
oInvoice.Lines.LineTotal = price;
oInvoice.Lines.Add();
int addInvoice = oInvoice.Add();
if (addInvoice == 0)
{
retval = HttpStatusCode.OK;
}
if (addInvoice < 0)
{
errorDescription = company.GetLastErrorDescription();
retval = HttpStatusCode.NotModified;
}
return (code: retval, description: errorDescription);
}
If an older version you would need to return a Tuple<HttpStatusCode, string>
I'd strongly recommend that a function that is creating invoices shouldn't know/care about http status codes at all.
All you need to know is whether it created a new invoice or not, and if not, why not. One option is to use an exception, but if "not modified, for reason xxx" is something you expect to happen reasonably often then that's probably not the best way forward. What you arguably want is some sort of discriminated union, but C# doesn't have a nice built in way of achieving that, so you could define a "response" type that can hold either a successful response or an error description. Then in your controller layer (that does need to know about http status codes etc), determine what sort of response to return to the client based on the contents of the response object. If you'd like the response object itself to be responsible for determining whether the error message should be exposed, ít could have a method that takes two lambdas, calling either one if in 'success' state, or the other (with the error description as a parameter) in the failed state. But that's arguably overkill.

(Async & await) vs (without Async & await) in Web API

I am new with Async and await using C# Programming. In WebAPI, we have created two API Controllers one with Async and await Programming and other is without that. We have done load testing using JMeter and we have got following results.
Users Sync Async
100 No Errors No Errors
500 No Errors No Errors
750 No Errors Errors - (59.0 %) - 502 Bad Gateway
763 No Errors Errors
764 No Errors Errors
765 Errors - (0.13 %) - 502 Bad Gateway Errors
1000 Errors Errors
Can you any please explain/suggest which approach is best or how can we proceed ?
API Code :
GetPersonalDetailsController - Async and await Used
public async Task<IHttpActionResult> GET([FromUri] RequestQueryListDTO objAPIRequest)
{
DateTime startResponseTime = DateTime.Now;
Response objResponse = null;
string strResponse = string.Empty;
var HeaderType = Request.Content.Headers.ContentType;
ProductBAL objProductBAL = null;
try
{
if (objAPIRequest != null)
{
Task<Response> tskGetProductDetails = Task<Response>.Run(() =>
{
objProductBAL = new ProductBAL();
return objProductBAL.GetProductDetails(objAPIRequest);
//Business Access Layer Logic calling
});
objResponse = await tskGetProductDetails;
}
else
{
objResponse = new Response();
objResponse.ReturnCode = -1;
objResponse.ReturnMessage = "Missing Parameters.";
}
}
catch (Exception ex)
{
\\ Exception Logging
}
finally
{
objProductBAL = null;
}
objResponse.ResponseTime = Math.Round((DateTime.Now - startResponseTime).TotalMilliseconds).ToString();
if (objResponse.ReturnCode == Convert.ToInt32(General.ReturnCode))
{
return Content<Response>(HttpStatusCode.BadRequest, objResponse);
}
else
{
return Ok(objResponse);
}
}
========================================================================
GetPDPController - Without using Async and await
public IHttpActionResult GET([FromUri] RequestQueryListDTO objAPIRequest)
{
DateTime startResponseTime = DateTime.Now;
Response objResponse = null;
string strResponse = string.Empty;
var HeaderType = Request.Content.Headers.ContentType;
try
{
if (objAPIRequest != null)
{
//Business Access Layer Logic calling
}
else
{
objResponse = new Response();
objResponse.ReturnCode = -1;
objResponse.ReturnMessage = "Missing Parameters.";
}
}
catch (Exception ex)
{
// Exception Logging Code
}
finally
{
objProductBAL = null;
}
objResponse.ResponseTime = Math.Round((DateTime.Now - startResponseTime).TotalMilliseconds).ToString();
if (objResponse.ReturnCode == Convert.ToInt32(General.ReturnCode))
{
return Content<Response>(HttpStatusCode.BadRequest, objResponse);
}
else
{
return Ok(objResponse);
}
}
My suggestion is have two methods, one Async and one not. That way you can test more.
GetProductDetails
GetProductDetailsAsync
you would then need to change the signature of the calling method aka GET
public IHttpActionResult GET([FromUri] RequestQueryListDTO objAPIRequest)
{
var objResponse = new Response();
//check the properties of objAPIRequest
if(bad)
{
//add stuff if you want
return Content<Response>(HttpStatusCode.BadRequest, objResponse);
}
//Business Access Layer Logic calling
//-----------------------
ProductBAL objProductBAL = new ProductBAL();
//you need to change this to async
var productDetails = objProductBAL.GetProductDetails(objAPIRequest);
//-----------------------
return Ok(objResponse);
}

Why detailed error message is not passed to HttpClient?

I am using the default Web Api controller that is auto generated. I am testing the validation and error handling in the client side. But somehow I have realised that the detail error message is not passed to client. Either if I throw HttpResponseException or returning IHttpActionResult in both cases the client is seeing only "Bad Request" but not the detailed message. Can anyone explain what is going wrong please?
public IHttpActionResult Delete(int id)
{
if (id <= 0)
{
var response = new HttpResponseMessage(HttpStatusCode.NotFound)
{
Content = new StringContent("Id should be greater than zero.", System.Text.Encoding.UTF8, "text/plain"),
StatusCode = HttpStatusCode.NotFound
};
throw new HttpResponseException(response) // Either this way
}
var itemToDelete = (from i in Values
where i.Id == id
select i).SingleOrDefault();
if (itemToDelete == null)
{
return BadRequest(string.Format("Unable to find a value for the Id {0}", id)); // Or This way
}
Values.Remove(itemToDelete);
return Ok();
}
client code is as:
private async static Task DeleteValue(int id)
{
var url = "http://localhost:13628/api/Values/" + id;
using (var client = new HttpClient())
{
var response = await client.DeleteAsync(url);
if (response.IsSuccessStatusCode)
{
await ReadValues();
}
else
{
Console.WriteLine(response.ReasonPhrase);
Console.WriteLine(response.StatusCode);
}
}
}
None of the above works??
Thx
In your client side change Console.WriteLine(response.ReasonPhrase);
to Console.WriteLine(response.Content.ReadAsStringAsync().Result);
and it will give the detailed error message.
Replace below code into Web API delete action. Use HttpResponseMessage as return tpye for api instead of IHttpActionResult
[HttpDelete]
[Route("{id:int:min(1)}")]
public async Task<HttpResponseMessage> DeleteAsync(int id)
{
if(id < 0 )
{
return await Task.FromResult<HttpResponseMessage>(Request.CreateResponse<string>(HttpStatusCode.BadRequest, "Id should be greater than zero."));
}
try
{
var itemToDelete = (from i in Values
where i.Id == id
select i).SingleOrDefault();
if (itemToDelete == null)
{
return await Task.FromResult<HttpResponseMessage>(Request.CreateResponse<string>(HttpStatusCode.NotFound,
string.Format("Unable to find a value for the Id {0}", id)));
}
Values.Remove(itemToDelete);
return await Task.FromResult<HttpResponseMessage>(Request.CreateResponse(HttpStatusCode.OK));
}
catch (Exception ex)
{
return Request.CreateResponse<string>(HttpStatusCode.InternalServerError, "Something went wrong."); // Default message if exception occured
}
}
And client Side:
private async static Task DeleteValue(int id)
{
var url = "http://localhost:13628/api/Values/" + id;
using (var client = new HttpClient())
{
var response = await client.DeleteAsync(url);
if (response.IsSuccessStatusCode)
{
await ReadValues();
}
else
{
var errorMessage = Newtonsoft.Json.JsonConvert.DeserializeObject<string>(await response.Content.ReadAsStringAsync());
// Here Newtonsoft.Json Package is used to deserialize response content
Console.WriteLine(errorMessage);
Console.WriteLine(response.StatusCode);
}
}
}
Above code is working at my side.

Categories