Headers Cache Control: No cache - asp.net-web-api

I am doing post request to an api !
string url = "http://xxx.xxx.xx.xx/api/QMn/Create";
var client = new HttpClient();
client.BaseAddress = new Uri(url);
// client.Headers.ContentType = new MediaTypeHeaderValue("application/json");
StringContent content = new StringContent(JsonConvert.SerializeObject(DataToSave), Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.PostAsync(url, content);
var result = await response.Content.ReadAsStringAsync();
the Api recieving request is this :
public void Create([FromBody] IEnumerable<QMSRejection> DataToSave)
{
try
{
_QMSRejection.Create(DataToSave);
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
I am receiving this error I am not able to understand why ?
{StatusCode: 204, ReasonPhrase: 'No Content',
Version: 1.1, Content: System.Net.Http.StreamContent,
Headers: { Cache-Control: no-cache
Date: Fri, 28 Aug 2020 06:18:43 GMT Pragma: no-cache
Server: Microsoft-IIS/10.0 X-Android-Received-Millis: 1598595526870
X-Android-Response-Source: NETWORK 204 X-Android-Selected-Protocol: http/1.1
X-Android-Sent-Millis: 1598595526011
X-AspNet-Version: 4.0.30319 X-Powered-By: ASP.NET Expires: -1 }}
Do I have to pass headers but I only require to pass body !

I solved the issue the error was from API Side and not client side ! There were validations in the API that was causing it to give such errors !

Related

HttpClient Returns 404 not found

I have a xamarin app that pull data from a webAPI. I check api address so many times and i am sure it is correct. When i debug my code i have 404 not found error from server. However when i copy and paste the URL to browser i have expected result. I couldn't figure out why my app return 404.
My Method:
public async Task<ICustomerType> GetById(int id)
{
string _token;
if (App.Current.Properties.ContainsKey("token"))
{
_token = (string)App.Current.Properties["token"];
}
else
{ _token = null; }
var webApiResponse =
_connector.PostAsync(
"api/Customer/get/id/" + id,
string.Empty, _token).Result;
var response = webApiResponse.Result.ToString();
var jObjectResponse = JObject.Parse(response);
ICustomerType customerTypeObj = null;
return customerTypeObj;
}
My bridge method to HttpClient's PostAsync method:
private async Task<TResponse> PostAsync(string requestPath, string
jsonContent, bool getToken, string token)
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(_apiUrl);
client.DefaultRequestHeaders.Accept.Clear();
var contentType = new MediaTypeWithQualityHeaderValue("application/json");
client.DefaultRequestHeaders.Accept.Add(contentType);
if (getToken)
{
token = GetApiTokenAsync().Result;
}
if (!string.IsNullOrEmpty(token))
{
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);
}
var httpContent = new StringContent(jsonContent, Encoding.UTF8, "application/json");
var response = client.PostAsync(requestPath, httpContent).Result;
var jsonData = await response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<TResponse>(jsonData);
}
Token: Correct
API Url: Correct(I check "/" signs from debug output.They are well placed. My Api like:
https://MyApi.net/api/Personel/get/id/1)
My Error:
response {StatusCode: 404, ReasonPhrase: 'Not Found', Version: 1.1, Content: System.Net.Http.StreamContent, Headers: { Request-Context:
appId=cid-v1:Some_String Server: Kestrel
Strict-Transport-Security: max-age=Some_Int Set-Cookie:
ARRAffinity=Some_String;Path=/;HttpOnly;Domain=MyDomain Date: Mon,
09 Jul 2018 07:54:19 GMT X-Powered-By: ASP.NET Content-Length: 0
}} System.Net.Http.HttpResponseMessage
your method verb in API is "GET" but you used "POST" in the client So in browser works because browser call "GET", but in the client doesn't work.
instead of :
var webApiResponse =
_connector.PostAsync(
"api/Customer/get/id/" + id,
string.Empty, _token).Result;
use :
var webApiResponse =
_connector.GetAsync(
"api/Customer/get/id/" + id,
string.Empty, _token).Result;

Error on data posting in xamarin.forms

Getting error while posting data to sql using .net Web API in xamarin.forms
StatusCode: 204, ReasonPhrase: 'No Content', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:{Cache-Control: no-cache Pragma: no-cache Server: Microsoft-IIS/8.5 X-AspNet-Version: 4.0.30319 X-Powered-By: ASP.NET Access-Control-Allow-Headers: Content-Type Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS Date: Thu, 17 Mar 2016 08:32:28 GMT Expires: -1 }}
this is my code to post data
T returnResult = default(T);
HttpClient client = null;
try
{
client = new HttpClient();
client.BaseAddress = new Uri(HostName);
client.DefaultRequestHeaders.Add("Accept", "application/json");
client.Timeout = new TimeSpan(0, 0, 15);
HttpResponseMessage result = null;
StringContent data = null;
if (content != null)
// data = new StringContent(JsonConvert.SerializeObject(content), UTF8Encoding.UTF8, "application/json");
data = new StringContent(JsonConvert.SerializeObject(content), Encoding.UTF8, "application/json");
if (method == HttpMethod.Get)
result = await client.GetAsync(endpoint);
if (method == HttpMethod.Put)
result = await client.PutAsync(endpoint, data);
if (method == HttpMethod.Delete)
result = await client.DeleteAsync(endpoint);
if (method == HttpMethod.Post)
result = await client.PostAsync(endpoint, data);
if (result != null)
{
if (result.IsSuccessStatusCode
&& result.StatusCode == System.Net.HttpStatusCode.OK)
{
var json = result.Content.ReadAsStringAsync().Result;
returnResult = JsonConvert.DeserializeObject<T>(json);
}
}
where should be the problem ?. My API is working fine and it is enabled CORS
Here is an example of how I am using PostAsync in my code, I think the error 'No Content' is referring on you are not sending anything to the server maybe? I hope this example helps:
public async Task<bool> PostAppointmet(AppointmentEntity anAppointment)
{
try{
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + App.apiToken);
const string resourceUri = ApiBaseAddress + "/citas";
string postBody = JsonConvert.SerializeObject(anAppointment);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = await client.PostAsync (resourceUri, new StringContent (postBody, Encoding.UTF8, "application/json"));
if (response.IsSuccessStatusCode) {
return true;
}
return false;
}
catch{
return false;
}
}
Where AppointmentEntity is my Model:
public class AppointmentEntity
{
public int doctor { get; set; }
public PatientEntity paciente { get; set; }
public DateEntity cita { get; set; }...
}
Try to use like this
var task = client.PostAsync(endpoint,content:data);

jqGrid dataUrl not returning value from server

I am using dataUrl to populate my dropdown in form edit of jqGrid, but i am not getting any response from server. what am i missing? fiddler shows no error
editoptions: {
dataUrl: "CurrencySetting.aspx/GetDet",
buildSelect: function (response) {
alert(response.responseText);
var data = typeof response === "string" ?
$.parseJSON(response.responseText) : response;
s = "<select>";
s += '<option value="0">------</option>';
$.each(data, function () {
s += '<option value="1">' + this.CurrencyCd +
'</option>';
});
return s + "</select>";
}
}
server code:
public static string GetDet()
{
SysDataContext db = new SysDataContext();
var query = (from SC in db.SysCurrencySettings
select new
{
SC.CurrencyCd
}).ToList();
return JsonConvert.SerializeObject(query);
}
HTTP response
HTTP/1.1 200 OK
Server: ASP.NET Development Server/10.0.0.0
Date: Thu, 22 Oct 2015 11:10:23 GMT
X-AspNet-Version: 4.0.30319
Cache-Control: private
Content-Type: text/html; charset=utf-8
Content-Length: 15497
Connection: Close

Dynamics CRM Plug-in with PATCH request

I'm writing a plug-in to send a PATCH request to the REST API whenever a new opportunity is created. But I keep getting the same error "400 Bad Request". However, I tested the URL in POSTMAN and it works fine. This is my code (the plug-in will call this method):
private async void MakeRequest(string requestUrl, ITracingService tracingService)
{
try
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(requestUrl);
client.DefaultRequestHeaders
.Accept
.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.TryAddWithoutValidation("Ocp-Apim-Subscription-Key", subscriptionKey);
HttpRequestMessage request = new HttpRequestMessage(new HttpMethod("PATCH"), "relativeAddress");
request.Content = new StringContent("{\"op\":\"replace\",\"path\":\"prescriptive-actions/status\",\"value\":\"Completed\",\"from\":\"New\"}", Encoding.UTF8, "application/json");
tracingService.Trace("requestUrl {0}", requestUrl);
var task = client.SendAsync(request)
.ContinueWith(responseTask =>
{
tracingService.Trace("responseTask {0}", responseTask.Result);
});
task.Wait();
}
catch (Exception ex)
{
tracingService.Trace("PROSPluginNotifyPAO Error: {0}", ex.ToString());
throw;
}
}
UPDATE 1
This is for CRM Online 2015. And below is the stack trace
requestUrl http://prospaodev.azure-api.net/hpho/prescriptive-actions/678391
responseTask StatusCode: 400, ReasonPhrase: 'Bad Request', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
Date: Tue, 06 Oct 2015 23:04:11 GMT
Content-Length: 0
}

Consuming Web Api's as HttpPost

Can somebody help me how to post an array of type long to a WebApi.
I think I have to use PostAsync from HttpClient, but I am not sure how to put array to HttpContent.
This is my controller.
[HttpPost]
[Authorize]
public void UpdateBatchesToReadyToShip(long[] batchIds)
{
// process request
}
And this is how I am trying to consume API
var buffer = Encoding.ASCII.GetBytes("username:password");
var authHeader = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(buffer));
client.DefaultRequestHeaders.Authorization = authHeader;
var arr = new long[3];
arr[0] = 10;
arr[1] = 12;
arr[2] = 13;
HttpContent content = new StringContent(string.Join(",", from i in arr select i.ToString()));
var task = client.PostAsync("https://<uri>/api/orderprocessing/UpdateBatchesToReadyToShip",content:content);
if (task.Result.StatusCode == HttpStatusCode.Unauthorized)
{
Console.WriteLine("wrong credentials");
}
else
{
//task.Result.EnsureSuccessStatusCode();
HttpResponseMessage message = task.Result;
if (message.IsSuccessStatusCode)
{
var details = message.Content.ReadAsStringAsync().Result;
Console.Write(details);
}
}
And I am getting this exception
{StatusCode: 500, ReasonPhrase: 'Internal Server Error', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
Pragma: no-cache
Cache-Control: no-cache
Date: Fri, 09 Nov 2012 12:37:44 GMT
Server: Microsoft-IIS/8.0
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Content-Length: 1060
Content-Type: application/json; charset=utf-8
Expires: -1
}}
Instead of using StringContent, you can use ObjectContent:
var content = new ObjectContent<long[]>(arr, new JsonMediaTypeFormatter());
var task = client.PostAsync(
"https://<uri>/api/orderprocessing/UpdateBatchesToReadyToShip",
content:content);

Resources