I am using WPF as Client and Web api as Service. For add new event click button and update button in WPF not returning to http post action in api controller and also returning error Internal server error.
Http Post method
[HttpPost]
public HttpResponseMessage PostEvent(EventFormModel event1)
{
if (ModelState.IsValid)
{
var command = new CreateOrUpdateEventCommand(event1.EventId, event1.EventAgenda, event1.Description, event1.EventDate, event1.Location, event1.UserId);
var result = commandBus.Submit(command);
if (result.Success)
{
var response = Request.CreateResponse(HttpStatusCode.Created, event1);
string uri = Url.Link("DefaultApi", new { id = event1.EventId });
response.Headers.Location = new Uri(uri);
return response;
}
}
else
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
}
throw new HttpResponseException(HttpStatusCode.BadRequest);
}
WPF click event:
private async void btnNewEvent_Click(object sender, RoutedEventArgs e)
{
var event1 = new Event()
{
EventAgenda = txtAgenda.Text,
Description = txtEventDescription.Text,
Location=txtLocation.Text,
UserId=Convert.ToInt32(txtUserId.Text),
EventId=Convert.ToInt32(txtEventId.Text),
EventDate=Convert.ToDateTime(dateEventDate.Text),
};
client.BaseAddress = new Uri("http://localhost:40926/api/Event");
// Add an Accept header for JSON format.
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
var response = client.PostAsJsonAsync("api/Event", event1).Result;
if (response.IsSuccessStatusCode)
{
MessageBox.Show("added" + response);
txtAgenda.Text = "";
txtEventDescription.Text = "";
txtLocation.Text = "";
txtUserId.Text = "";
txtEventId.Text = "";
dateEventDate.Text = "";
}
else
{
MessageBox.Show("Error Code" + response.StatusCode + " : Message - " + response.ReasonPhrase);
}
}
Event class in WPF application:
public class Event
{
public int EventId { get; set; }
public int UserId { get; set; }
// [Required(ErrorMessage = "Agenda Required")]
//[Display(Name = "Movie Name")]
public string EventAgenda { get; set; }
// [Required(ErrorMessage = "Location Required")]
public string Location { get; set; }
// [Required(ErrorMessage = "Date Required")]
public DateTime EventDate { get; set; }
public string Description { get; set; }
// public string ReminderType { get; set; }
}
I used breakpoints near post action and also click event. but in click event near
var response = client.PostAsJsonAsync("api/Event", event1).Result; not returing to api post method and returning Response status code does not indicate success: 500 (Internal Server Error). Similar issue for Update also
-Thanks Sindhu
You included some parts of the URI twice.
client.BaseAddress = new Uri("http://localhost:40926/api/Event");
// Add an Accept header for JSON format.
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
var response = client.PostAsJsonAsync("api/Event", event1).Result;
You duplicated "api/Event". And would get the URI, api/Event/api/Event/. For your BaseAddress you only need hostname and port.
e.g.
client.BaseAddress = new Uri("http://localhost:40926");
var response = client.PostAsJsonAsync("api/Event", event1).Result;
Also you are getting a 500 Internal Server error from somewhere else in your sever code. I can't where right now.
Related
I have this api in php that works ok when sending data from an html form.
<?php
include_once 'apiAppMovil.php';
$api = new AppMovil();
$error = '';
if(isset($_POST["nombre"]) && isset($_POST["ape"]) && isset($_POST["email"]) && isset($_POST["pass"])){
if($api->subirImagen($_FILES['foto'])){
$item = array(
"nombre" => $_POST["nombre"],
"ape" => $_POST["ape"],
"email" => $_POST["email"],
"pass" => $_POST["pass"],
"foto" => $api->getImagen() //Not used
);
$api->add($item);
}else{
$api->error('Error con el archivo: ' . $api->getError());
}
}
else{
$api->error('Error al llamar a la API');
}
?>
I want to send data but from c#. My class is the following:
public partial class Root
{
[JsonProperty("items")]
public Item[] Items { get; set; }
}
public partial class Item
{/*
[JsonProperty("id")]
[JsonConverter(typeof(ParseStringConverter))]
public long Id { get; set; }*/
[JsonProperty("nombre")]
public string Nombre { get; set; }
[JsonProperty("ape")]
public string Ape { get; set; }
[JsonProperty("email")]
public string Email { get; set; }
[JsonProperty("pass")]
public string Pass { get; set; }
[JsonProperty("foto")] //Not Used
public string Foto { get; set; }
}
and my method is:
private async Task SignUpApiPost()
{
var data = new Item
{
Nombre = "Eric",
Ape = "Pino",
Pass = "M2022",
Email = "ericpinodiaz#gmail.com",
Foto = "default.jpeg" //Not Used
};
// Serialize our concrete class into a JSON String
var json = JsonConvert.SerializeObject(data);
// Wrap our JSON inside a StringContent which then can be used by the HttpClient class
var httpContent = new StringContent(json.ToString(), Encoding.UTF8, "application/json");
var httpClient = new HttpClient();
// Do the actual request and await the response
var response = await httpClient.PostAsync("https://app.domainexample.com/rest/add.php", httpContent);
if (response.StatusCode == System.Net.HttpStatusCode.OK)
{
//do thing
}
}
But I can't get the data to arrive, I have the errors "Error al llamar a la API" from Api php.
I think the problem is that var data = new Item{ is not declared correctly, can you help me and tell me where I am going wrong?
Thank you.
Edit:
I add the html with which it works correctly:
You should try something like the one below.
client.BaseAddress = new Uri("your url");
//HTTP POST
var postTask = client.PostAsJsonAsync<StudentViewModel>("your parameter name", Item);
postTask.Wait();
var result = postTask.Result;
if (result.IsSuccessStatusCode)
{
//do something
}
I am calling the API for creating a meeting on a fixed date & time. I am using Microsoft Graph API for this. Here is the URL
var url = "https://graph.microsoft.com/v1.0/me/events";
I have taken care of the Authentication part and my code does the following thing to send the JSON response to the API
private async void sendInvites_Click(object sender, RoutedEventArgs e)
{
var httpClient = new System.Net.Http.HttpClient();
System.Net.Http.HttpResponseMessage response;
var url = "https://graph.microsoft.com/v1.0/me/events";
CIBC.Models.SendMeetingInvites.RootObject obj = new CIBC.Models.SendMeetingInvites.RootObject();
CIBC.Models.SendMeetingInvites.Location loc = new CIBC.Models.SendMeetingInvites.Location();
loc.displayName = GlobalVariables.MeetingRoomName;
//loc.RoomEmailAddress = GlobalVariables.meetingRoomEmailID.ToString();
obj.subject = "Maths";
CIBC.Models.SendMeetingInvites.Body body = new CIBC.Models.SendMeetingInvites.Body();
body.content = "Its a booking for follow up meeting";
body.contentType = "HTML";
obj.body = body;
List<CIBC.Models.SendMeetingInvites.Attendee> attens = new List<Models.SendMeetingInvites.Attendee>();
for(int i=0;i<GlobalVariables.NumberOfParticipant.Count;i++)
{
CIBC.Models.SendMeetingInvites.EmailAddress email = new CIBC.Models.SendMeetingInvites.EmailAddress();
CIBC.Models.SendMeetingInvites.Attendee atten = new CIBC.Models.SendMeetingInvites.Attendee();
email.address = GlobalVariables.NumberOfParticipant[i].ParticipantADdress;
atten.emailAddress = email;
atten.type = "Required";
attens.Add(atten);
}
CIBC.Models.SendMeetingInvites.Start start = new CIBC.Models.SendMeetingInvites.Start();
start.dateTime = GlobalVariables.sendMeetingInviteStartDate;
start.timeZone = "UTC";
obj.start = start;
CIBC.Models.SendMeetingInvites.End end = new CIBC.Models.SendMeetingInvites.End();
end.dateTime = GlobalVariables.sendMeetingInviteEndTime;
end.timeZone = "UTC";
obj.end = end;
obj.attendees = attens;
obj.location = loc;
string postBody = Newtonsoft.Json.JsonConvert.SerializeObject(obj);
// var postBody1 = "{'Subject':'Testing Organizer - 12','Location':{'DisplayName':'Some place'}," +
//"'Start': {'DateTime': '2016-07-15T15:00:00.0000000', 'TimeZone':'UTC'}," +
//"'End': {'DateTime': '2016-07-15T15:30:00.0000000', 'TimeZone':'UTC'}," +
//"'Body':{'Content': 'This is a test of Grap API.', 'ContentType':'Text'}," +
//"'IsOrganizer':'False','Organizer':{'EmailAddress': " + "{'Address':'organizer#some.com'} }}";
// var requestString = #"{"subject":"My event","start":{"dateTime":"2017-09-25T07:44:27.448Z","timeZone":"UTC"},"end":{"dateTime":"2017-10-02T07:44:27.448Z","timeZone":"UTC"}}"";
var request = new System.Net.Http.HttpRequestMessage(System.Net.Http.HttpMethod.Post, url);
//Add the token in Authorization header
request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer",GlobalVariables.Token);
request.Content = new StringContent(postBody, UTF8Encoding.UTF8, "application/json");
response = await httpClient.SendAsync(request);
if (response.IsSuccessStatusCode)
{ }
// return await response.Content.ReadAsStringAsync();
else
{
}
//return "";
}
Here is the class file that I am using to pass to the HTTPResponse Message
namespace CIBC.Models.SendMeetingInvites
{
public class Body
{
public string contentType { get; set; }
public string content { get; set; }
}
public class Start
{
public DateTime dateTime { get; set; }
public string timeZone { get; set; }
}
public class End
{
public DateTime dateTime { get; set; }
public string timeZone { get; set; }
}
public class Location
{
public string displayName { get; set; }
//public string RoomEmailAddress { get; set; }
}
public class EmailAddress
{
public string address { get; set; }
public string name { get; set; }
}
public class Attendee
{
public EmailAddress emailAddress { get; set; }
public string type { get; set; }
}
public class RootObject
{
public string subject { get; set; }
public Body body { get; set; }
public Start start { get; set; }
public End end { get; set; }
public Location location { get; set; }
public List<Attendee> attendees { get; set; }
}
}
My requirement is to send a meeting invite to all the users and also mentioning the Room Details like Name& Email ID of the room.
I tried adding a RoomEmail address in the Request as under The Location class
public string RoomEmailAddress { get; set; }
When I tested this using Microsoft Graph Explorer website , i got the error message
{
"error": {
"code": "RequestBodyRead",
"message": "The property 'RoomEmailAddress' does not exist on type 'Microsoft.OutlookServices.Location'. Make sure to only use
property names that are defined by the type or mark the type as open
type.",
"innerError": {
"request-id": "1883d87d-a5d6-4357-a699-7c112da0e56b",
"date": "2017-09-26T12:03:50"
}
} }
How do I make sure that whenever I create a meeting request , I can assign a room to it?
Currently I am just able to pass DisplayName while sending the Request to the URL.
Once I remove the Email Address property (I added myself ), the code returns Success.
Any workarounds so that I can send the room email address also so that the room also receives a copy of the meeting invite ?
Add the room as an attendee with "type": "Resource". Then add the room's display name in the location property.
I have below code to send email to multiple email ids and am using RestSharp request and response with MailGun API
var emodel = model as EmailViewModel;
var context = HttpContext.Current;
var from = "KG <" + emodel.FromEmail[0] + ">";
var client = new RestClient
{
BaseUrl = new Uri("https://api.mailgun.net/v3"),
Authenticator = new HttpBasicAuthenticator("api", WebConfigurationManager.AppSettings["MGKey"])
};
foreach(var to in emodel.EmailID)
{
var request = new RestRequest();
request.AddParameter("domain",
"domain.com", ParameterType.UrlSegment);
request.Resource = "{domain}/messages";
request.AddParameter("from", from);
request.AddParameter("subject", emodel.Subject ? ? "No Subject");
var body = emodel.Message ? ? "Empty Message";
request.AddParameter("html", body);
request.Method = Method.POST;
request.AddParameter("to", to);
var json = new JavaScriptSerializer();
client.ExecuteAsync(request, r => {
var content = json.Deserialize<Dictionary<string,string >>(r.Content);
if (content != null && r.ResponseStatus == ResponseStatus.Completed && r.StatusCode == HttpStatusCode.OK)
{
msgId=content.msgID;
}
if (msgId != "")
{
using(_db = new DBcontext())
{
var message = new tblMsg {
MDSent = DateTime.Today.Date,
MMsg = WebUtility.HtmlEncode(emodel.Message),
MMsgStatus = EventTypes.Stored.ToString(),
MMsgType = true,
MSByID = from,
MSByUser = loggedInUser,
MSID = msgId,
MSub = emodel.Subject ? ? "No subject",
MToID = to
};
_db.Entry(message).State = EntityState.Added;
_db.SaveChanges();
}
}
else {
LogError.LogMessage(r.ErrorMessage, context);
}
});
}
EmailViewModel.cs
public class EmailViewModel
{
public string[] EmailID { get; set; }
public SelectList Emails { get; set; }
public string[] Names { get; set; }
public string Message { get; set; }
public string[] FromEmail { get; set; }
public SelectList FromEmails { get; set; }
public bool HasAttachment { get; set; }
public string AttachmentPath { get; set; }
public int AttachmentCount { get; set; }
public string Subject { get; set; }
}
The problem over here is when I send an email to multiple ids, because of client.ExecuteAsync line which is inside for-loop, it will fetch async response multiple times and store it in content and before message record saves into database, it gets replaced with the next async response from API and hence only one record gets saved in database. Is there any mechanism in C#, wherein I can hold variable message value until its saved to database? I tried using lock on content variable, but it did not help.. Hoping to find some help.
I am calling an external service using GetAsync() and passing parameters in query string. When i check the content in the response, i don't see anything returned, however it returns 200 OK and in fiddler it returns me the XML response correctly. I need the XML response to get de-serialize to an C# object and then further save it to DB.
Things tried:
1) Tried this by adding this setting in global- app_start(), It didn't help
GlobalConfiguration.Configuration.Formatters.XmlFormatter.UseXmlSerializer = true;
2) Created an object and tried to sent it via GetAysnc, that didn't help either.
public class Request
{
[XmlElement]
public string XML { get; set; }
[XmlElement]
public List<string> ProNumber { get; set; }
}
2) Should i try passing parameters in query string and expect json result? if i add mediatyperformatter to application/json?
Here is my code:
public async Task<HttpResponseMessage> GetData()
{
string requestString = "&xml=Y&PRONumber=82040X,03117X";
string result = "";
string url = #"http://my.yrc.com/dynamic/national/servlet?CONTROLLER=com.rdwy.ec.rextracking.http.controller.PublicTrailerHistoryAPIController";
try
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(url);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml"));
HttpResponseMessage response = await client.GetAsync(url+requestString);
if (response.IsSuccessStatusCode)
{
return response;
}
}
}
catch (Exception ex)
{
result = ex.Message;
}
return null;
}
EDIT:
Shipments scp = null;
XmlRootAttribute xRoot = new XmlRootAttribute();
xRoot.ElementName = "Shipment";
xRoot.IsNullable = true;
XmlSerializer serializer = new XmlSerializer(typeof(Shipment), xRoot);
using (Stream stream = response.Content.ReadAsStreamAsync().Result)
{
scp = (Shipments)serializer.Deserialize(stream);
}
Model:
public class Shipments
{
[XmlArrayItem(Type = typeof(Shipment))]
public Shipment[] Shipment;
}
public class Shipment
{
[XmlAttribute()]
public int returnCode { get; set; }
.................
..............
Getting error:<SHIPMENTS xmlns=''> was not expected.
Any help on this is much appreciated.
Thanks,
WH
This worked for me -
var client = new HttpClient();
var data = client.GetStringAsync("http://my.yrc.com/dynamic/national/servlet?CONTROLLER=com.rdwy.ec.rextracking.http.controller.PublicTrailerHistoryAPIController&xml=Y&PRONumber=82040X,03117X").Result;
var ser = new XmlSerializer(typeof(Shipments));
var t = (Shipments)ser.Deserialize(new StringReader(data));
public class Shipment
{
public string returnCode { get; set; }
public string returnMessage { get; set; }
public string freightBillNumber { get; set; }
//props
}
[XmlRoot(ElementName = "SHIPMENTS")]
public class Shipments
{
[XmlElement(ElementName = "SHIPMENT")]
public List<Shipment> SHIPMENT { get; set; }
}
EDIT
this works as well -
var data = client.GetStreamAsync("http://my.yrc.com/dynamic/national/servlet?CONTROLLER=com.rdwy.ec.rextracking.http.controller.PublicTrailerHistoryAPIController&xml=Y&PRONumber=82040X,03117X").Result;
EDIT
works as well -
var client = new HttpClient();
var data = client.GetAsync("http://my.yrc.com/dynamic/national/servlet?CONTROLLER=com.rdwy.ec.rextracking.http.controller.PublicTrailerHistoryAPIController&xml=Y&PRONumber=82040X,03117X").Result;
var ser = new XmlSerializer(typeof(Shipments));
var t = (Shipments)ser.Deserialize(data.Content.ReadAsStreamAsync().Result);
For some reason, I'm receiving a 403: Forbidden exception in Visual Studio when I try fetching JSON results from a web API I'm using. When I try using the web API URL in my web browser, everything shows up as it should. Any ideas?
The main code:
theURI = "http://isitup.org/duckduckgo.com.json";
HttpClient httpClient = new HttpClient();
httpClient.MaxResponseContentBufferSize = Int32.MaxValue;
var jsonResponse = await httpClient.GetStringAsync(theURI);
var rootObject = JsonConvert.DeserializeObject<StatusMessage.RootObject>(jsonResponse);
int statuscode = rootObject.status_code;
if (statuscode == 1)
{
txtStatus.Text = "Website is UP!";
}
else if (statuscode == 2)
{
txtStatus.Text = "Website is DOWN!";
}
else
{
txtStatus.Text = "Invalid domain!";
}
and the class file
class StatusMessage
{
public class RootObject
{
public string domain { get; set; }
public int port { get; set; }
public int status_code { get; set; }
public object response_ip { get; set; }
public object response_code { get; set; }
public object response_time { get; set; }
}
}
Seems like the server responds you 403 if you are using the default user agent. If you change it to chrome user agent the server is answering properly.
var url = new Uri("http://isitup.org/duckduckgo.com.json");
var req = new HttpClient();
var message = new HttpRequestMessage(HttpMethod.Get, url);
message.Headers.Add("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1309.0 Safari/537.17");
var response = await req.SendAsync(message);
var responseString = await response.Content.ReadAsStringAsync();