While accessing web Api in xamarin.forms i am getting this error below which is i am unable to Solve
{StatusCode: 404, ReasonPhrase: 'Not Found', Version: 1.1, Content:
System.Net.Http.StreamContent, Headers: { Server: Microsoft-IIS/10.0
X-Powered-By: ASP.NET Date: Fri, 09 Feb 2018 12:50:00 GMT
Content-Type: text/html Content-Length: 1245 }}
This is my web Api Code.
public IList<TCourse> GetData()
{
try
{
using (var context = new HCMSEntities())
{
var cli = (from b in context.tblTrainingCourses
orderby b.CourseID
select new TCourse { CourseID = b.CourseID, Course = b.Course }
).ToList();
return cli;
}
}
catch (Exception ex)
{
return null;
}
}
And here is the code which is consuming the api and i am getting above error.
public async Task Index()
{
List<TCourse> EmpInfo = new List<TCourse>();
try
{
using (var client = new HttpClient())
{
//Passing service base url
client.BaseAddress = new Uri("http://10.20.2.62/");
client.DefaultRequestHeaders.Clear();
//Define request data format
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
//Sending request to find web api REST service resource GetAllEmployees using HttpClient
HttpResponseMessage Res = await client.GetAsync("api/Course");
//Checking the response is successful or not which is sent using HttpClient
if (Res.IsSuccessStatusCode)
{
//Storing the response details recieved from web api
var EmpResponse = Res.Content.ReadAsStringAsync().Result;
//Deserializing the response recieved from web api and storing into the Employee list
EmpInfo = JsonConvert.DeserializeObject<List<TCourse>>(EmpResponse);
}
}
}
catch (Exception e)
{
}
}
The web Api is not deployed.I tried http://localhost/ in base address than i switched to Ip.
no idea whats wrong and where.
kindly Guide.
Related
I'm developing a Xamarin forms app that uses ASP.NET Web Application template. I followed this tutorial on YouTube. I'm having problem using the PostAsync method. The web api itself can start OK via IIS Chrome on my local machine, but not via the emulator. I printed the response message, displayed as
StatusCode: 400, ReasonPhrase: 'Bad Request', Version: 1.1, Content:
System.Net.Http.HttpConnection+HttpConnectionResponseContent, Headers:
{
Server: Microsoft-HTTPAPI/2.0
Date: Sun, 26 Sep 2021 06:53:22 GMT
Connection: close
Content-Type: text/html; charset=us-ascii
Content-Length: 334
}
Here's the service class which contains the RegisterAsync method
public class UserService
{
private string androidApiUrl = "https://10.0.2.2:44358/api/Account/Register";
private string iOSApiUrl = "https://localhost:44358/api/Account/Register";
private HttpClient client;
public UserService()
{
var httpClientHandler = new HttpClientHandler();
httpClientHandler.ServerCertificateCustomValidationCallback =
(msg, cert, chain, err) => { return true; };
client = new HttpClient(httpClientHandler);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
}
public async Task<bool> RegisterAsync(string username, string pswd, string confmPswd)
{
var newAccount = new ModelAccount
{
Email = username,
Password = pswd,
ConfirmPassword = confmPswd
};
var json = JsonConvert.SerializeObject(newAccount);
HttpContent content = new StringContent(json);
content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json")
{
CharSet = Encoding.UTF8.WebName
};
try
{
var response = await client.PostAsync(androidApiUrl, content);
Console.WriteLine(response.ToString());
Console.WriteLine(response.ReasonPhrase);
Console.WriteLine(response);
return response.IsSuccessStatusCode;
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
throw e;
}
}
}
Here's the WebAPI's properties...
Here's the ModelConvert which is json-serialized.
class ModelAccount
{
public string Email { get; set; }
public string Password { get; set; }
public string ConfirmPassword { get; set; }
}
If it makes any different if I changed the port number to 61902 as suggest by this blog, it still won't work.
Thank you
Edit:
as requested by #Aristos, here are the port numbers connected.
On the settings you have define the port number - usually this is a random port so probably have change on your system. Check on witch port your local iis is running when you run visual studio and change that according.
My API has a method of type Patch that I need to call from the client. This method is:
[HttpPatch("{id}")]
public StatusCodeResult Patch(int id, [FromBody]JsonPatchDocument<Reservation> patch)
{
Reservation res = Get(id);
if (res != null)
{
patch.ApplyTo(res);
return Ok();
}
return NotFound();
}
I am trying to call it from my client whose code is:
[HttpPost]
public async Task<IActionResult> UpdateReservationPatch(int id, Reservation reservation)
{
using (var httpClient = new HttpClient())
{
var request = new HttpRequestMessage
{
RequestUri = new Uri("http://localhost:8888/api/Reservation/" + id),
Method = new HttpMethod("Patch"),
Content = new StringContent("[{ \"op\":\"replace\", \"path\":\"Name\", \"value\":\"" + reservation.Name + "\"},{ \"op\":\"replace\", \"path\":\"StartLocation\", \"value\":\"" + reservation.StartLocation + "\"}]", Encoding.UTF8, "application/json")
};
var response = await httpClient.SendAsync(request);
}
return RedirectToAction("Index");
}
I am failing to do so and getting error.
StatusCode: 400, ReasonPhrase: 'Bad Request', Version: 1.1, Content: System.Net.Http.HttpConnectionResponseContent, Headers:
{
Server: Microsoft-IIS/10.0
X-Powered-By: ASP.NET
Date: Tue, 28 Jul 2020 12:25:24 GMT
Content-Type: application/problem+json; charset=utf-8
Content-Length: 370
}}
What can be the problem?
I have created the simple login page in xamarin.forms,i have API for those logins,while running at postman iam getting the output,but while logging from the simulator iam getting the following error.
{StatusCode: 404, ReasonPhrase: 'Not Found', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
Cache-Control: private
Server: Microsoft-IIS/8.0
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Set-Cookie: ARRAffinity=639506ba4afdd530b4429c0d57e89977accb4b666a1e17dbe3fcc5c1fce369d5;Path=/;HttpOnly;Domain=snovahub.azurewebsites.net
Date: Wed, 13 Sep 2017 13:23:00 GMT
Content-Length: 3485
Content-Type: text/html; charset=utf-8
}}
My Api method is as follows:
#region Get results from api
public static async Task<T> GetResultFromApi<T>(string serviceUrl,bool isTrue=true)
{
try
{
GetConnection();
var response = await _httpClient.GetAsync(new Uri(SnovaHubApiUrls.SnovaHubWebUrl + serviceUrl));
var stringAsync = await response.Content.ReadAsStringAsync();
if (response.IsSuccessStatusCode)
{
var responseJson = stringAsync;
return JsonConvert.DeserializeObject<T>(responseJson);
}
LoggingManager.Error("Received error response: " + stringAsync);
return default(T);
}
catch (Exception exception)
{
LoggingManager.Error(exception);
return default(T);
}
}
#endregion
The issue is that you are setting the HttpClient.BaseAddress and then also passing in a full URL when calling HttpClient.GetAsync(). You need to choose one or the other. So:
Option 1:
private static void GetConnection() {
if (_httpClient == null) {
_httpClient = new HttpClient { BaseAddress = new Uri(SnovaHubApiUrls.SnovaHubWebUrl) }; //You MUST place a / (slash) at the end of your BaseAddress ("http://something.com/api/" for example)
}
}
Then in your GetResultFromApi() method:
...
var response = await _httpClient.GetAsync(serviceUrl); //You MUST NOT place a slash at the beginning of 'serviceUrl' when using BaseAddress
Option 2:
private static void GetConnection() {
if (_httpClient == null) {
_httpClient = new HttpClient(); //Removed BaseAddress
}
}
Then in your GetResultFromApi() method:
...
var response = await _httpClient.GetAsync(new Uri(SnovaHubApiUrls.SnovaHubWebUrl + serviceUrl)); //Passing full URL
I built a website using ASP.NET MVC and Knockoutjs. This is hosted on IIS on Windows Sever 2012. There is another web application where I use ajax to POST and that application does not give any errors. The Submit button on the website is binded using the click bind to this function. This works when I run it in Debug mode on the localhost.
self.SubmitEvaluation = function () {
reqUrl = "/Home/SubmitEvaluation";
$.ajax({
type: "POST",
url: reqUrl,
data: JSON.stringify({ evaluation: ko.toJSON(self) }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
if (response == 1) {
self.EvalComplete(true);
} else {
self.EvalComplete(false);
alert("Submission Failed. Please resubmit!!!")
}
},
error: function (jqXHR, exception) {
if (jqXHR.status === 0) {
alert('Not connect.\n Verify Network.');
} else if (jqXHR.status == 404) {
alert('Requested page not found. [404]');
} else if (jqXHR.status == 500) {
alert('Internal Server Error [500].'+exception.toString());
} else if (exception === 'parsererror') {
alert('Requested JSON parse failed.');
} else if (exception === 'timeout') {
alert('Time out error.');
} else if (exception === 'abort') {
alert('Ajax request aborted.');
} else {
alert('Uncaught Error.\n' + jqXHR.responseText);
}
}
});
In the home controller I have these two web methods.
[HttpGet]
public string Test()
{
Logger.Logger.WriteLog("Test", "Inside Test");
TestModel product = new TestModel();
product.Name = "Apple";
product.Price = "3.99M";
return JsonConvert.SerializeObject(product);
}
[HttpPost]
public int SubmitEvaluation(string evaluation)
{
Logger.Logger.WriteLog("Submitevaluation", "Inside SubmitEvaluation");
int result = -1;
try
{
EvaluationModel eval = JsonConvert.DeserializeObject<EvaluationModel>(evaluation);
MySqlConnection conn = new MySqlConnection(connStr);
conn.Open();
string sql = "INSERT INTO xyz table blah blah blah";
MySqlCommand cmd = new MySqlCommand(sql, conn);
result = cmd.ExecuteNonQuery();
}
catch(Exception ex)
{
Logger.WriteLog("Submitevaluation", ex.ToString());
}
return result;
}
I receive Internal Sever Error 500 from the Ajax request when I click on the Submit button.
But if I do this http://xxx.xxx.xxx.xxx/Home/Test I get the json result back {"Name":"Apple","Price":"3.99M"}.
Response header from Fiddler
HTTP/1.1 500 Internal Server Error
Cache-Control: private
Content-Type: text/html; charset=utf-8
Server: Microsoft-IIS/8.0
X-AspNetMvc-Version: 4.0
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Thu, 09 Jan 2014 16:22:16 GMT
Content-Length: 276
After turning on customer errors and detailed error message I am receiving this message.
Could not load file or assembly 'MySql.Data, Version=6.8.3.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d' or one of its dependencies. The system cannot find the file specified
I downloaded the Mysql connector from http://dev.mysql.com/downloads/connector/net/ and I added the assembly by right clicking on References > Extensions and selecting the 4.0 version. I also tried the 4.5.
Uninstalled 6.8 and downloaded 6.7. Works now.
I'm trying to fetch FreeBusy data from my Google calendar using the .NET client API V3.
The following code allows me to login using a service authentication and fetch the calendar list and calendar settings. I can also fetch the events as shown.
To make this work I have shared my calendar with my development Id:
<my-id>#developer.gserviceaccount.com
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Google.Apis.Calendar;
using Google.Apis.Calendar.v3;
using Google.Apis.Authentication;
using Google.Apis.Authentication.OAuth2;
using Google.Apis.Authentication.OAuth2.DotNetOpenAuth;
using DotNetOpenAuth.OAuth2;
using System.Diagnostics;
using Google.Apis.Calendar.v3.Data;
using System.Security.Cryptography.X509Certificates;
using Google.Apis.Discovery;
using Google.Apis.Drive.v2;
using Google.Apis.Util;
namespace consoleGoogleResearch
{
class Program
{
private const string SERVICE_ACCOUNT_EMAIL = "<your-value>#developer.gserviceaccount.com";
private const string SERVICE_ACCOUNT_PKCS12_FILE_PATH = #"<path-to\<your-value>-privatekey.p12";
/// <summary>
/// Build a Calendar service object authorized with the service account.
/// </summary>
/// <returns>Drive service object.</returns>
static CalendarService BuildCalendarService()
{
AssertionFlowClient client = new AssertionFlowClient(
GoogleAuthenticationServer.Description, new X509Certificate2(SERVICE_ACCOUNT_PKCS12_FILE_PATH, "notasecret", X509KeyStorageFlags.Exportable))
{
Scope = CalendarService.Scopes.Calendar.GetStringValue(),
ServiceAccountId = SERVICE_ACCOUNT_EMAIL,
};
OAuth2Authenticator<AssertionFlowClient> authenticator = new OAuth2Authenticator<AssertionFlowClient>(client, AssertionFlowClient.GetState);
return new CalendarService(authenticator);
}
public static void Main(string[] args)
{
var service = BuildCalendarService();
// Get the calendar service
Google.Apis.Calendar.v3.CalendarListResource.ListRequest clrq = service.CalendarList.List();
var result = clrq.Fetch();
// Prove we can get the settings.
SettingsResource.ListRequest slr = service.Settings.List();
var sr = slr.Fetch();
try
{
Console.WriteLine("Calendars: ");
foreach (CalendarListEntry calendar in result.Items)
{
Console.WriteLine("{0}", calendar.Id);
Console.WriteLine("\tAppointments:");
Google.Apis.Calendar.v3.EventsResource.ListRequest elr = service.Events.List(calendar.Id);
var events = elr.Fetch();
if (events.Items != null)
{
foreach (Event e in events.Items)
{
Console.WriteLine("\tSummary: {0}, Location: {1}", e.Summary, e.Location);
if (e.IsAllDayEvent())
{
Console.WriteLine("\t\tAll Day: {0}", e.Start.GetDateTime().ToLongDateString());
}
else
{
Console.WriteLine("\t\tFrom: {0}", e.Start.GetDateTime());
Console.WriteLine("\t\tTo: {0}", e.End.GetDateTime());
}
if (e.Attendees != null)
{
foreach (var att in e.Attendees)
{
Console.WriteLine("Attendee:\t\t\t{0}<{1}>", att.DisplayName, att.Email);
}
}
Console.WriteLine();
}
}
}
}
catch (Exception ex)
{
log.DebugFormat("Error: {0}", ex.Message);
}
// Attempt to get free busy data.
FreebusyResource.QueryRequest fbq = service.Freebusy.Query(new FreeBusyRequest());
FreeBusyRequestItem c = new FreeBusyRequestItem();
c.Id = "<your calendar id>";
fbq.Body.Items = new List<FreeBusyRequestItem>();
fbq.Body.Items.Add(c);
fbq.Body.TimeZone = "Europe/London";
fbq.Body.TimeMin = "2013-01-101T00:00:00.000Z";
fbq.Body.TimeMax = "2013-01-301T00:00:00.000Z";
// This call fails with global bad request
var fbres = fbq.Fetch();
Console.ReadKey();
}
}
static internal class Extensions
{
static internal DateTime GetDateTime(this EventDateTime edt)
{
if (String.IsNullOrEmpty(edt.DateTime))
{
if (String.IsNullOrEmpty(edt.Date))
{
return DateTime.MinValue;
}
else
{
return DateTime.Parse(edt.Date);
}
}
else
{
return DateTime.Parse(edt.DateTime);
}
}
static internal Boolean IsAllDayEvent(this Event e)
{
return (e.Start.DateTime == null && e.Start.Date != null);
}
}
}
However the code that attempts to fetch free busy information always receives a "bad request" error.
I have checked the request sent using fiddler and as far as I can see it is correct.
POST https://www.googleapis.com/calendar/v3/freeBusy?alt=json&prettyPrint=true HTTP/1.1
Authorization: Bearer <removed>
Content-Type: application/json; charset=utf-8
User-Agent: ConsoleApplication1 google-api-dotnet-client/ Win32NT/6.1.7601.65536 (gzip)
Host: www.googleapis.com
Content-Length: 144
Accept-Encoding: gzip, deflate
{"items":[{"id":"apps.vivid#gmail.com"}],"timeMax":"2013-01-301T00:00:00.000Z","timeMin":"2013-01-101T00:00:00.000Z","timeZone":"Europe/London"}
Can anyone tell me why I'm receiving the bad request error and more importantly how to fix it?
Many thanks
Chris.
The answer is in the comment above, I made a mistake with the dates.