I am trying to output a small popup-like window to the user saying either the restful command was successfully accepted or not (and display the Http Code).
I am really looking for direction on how to do this properly in ASP.NET MVC.
Controller Function
public void ExportJira()
{
string postUrl = "https://somewebsite.org/rest/api/2/issue";
var httpWebRequest = (HttpWebRequest)WebRequest.Create(postUrl);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
//Using Service Account for Demo Jira Instance
httpWebRequest.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes("FakeAccount:fakePw"));
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = #"{""fields"":{""project"":{""key"": ""SDR""},""summary"": ""This is SDR Web App"",""issuetype"" : {""id"":""3""}}}";
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
HttpWebResponse httpResponse = null;
try
{
httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
System.Diagnostics.Debug.WriteLine("Errorcode: {0}", (int)httpResponse.StatusCode);
System.Diagnostics.Debug.WriteLine("Support Headers: \n" + httpResponse.SupportsHeaders + "\n");
System.Diagnostics.Debug.WriteLine("Headers: \n" + httpResponse.Headers + "\n");
TempData["msg"] = "<script>alert('Success!" + (int)httpResponse.StatusCode + "');</script>";
}
}
catch (WebException e)
{
if (e.Status == WebExceptionStatus.ProtocolError)
{
httpResponse = (HttpWebResponse)e.Response;
TempData["msg"] = "<script>alert('Failed!" + (int)httpResponse.StatusCode + "');</script>";
}
else
{
TempData["msg"] = "<script>alert('Failed!" + (int)httpResponse.StatusCode + "');</script>";
}
}
finally
{
if (httpResponse != null)
{
httpResponse.Close();
}
}
}
}
View Code
#Html.ActionLink("Export to Jira", "ExportJira", null, new { id = "myLink" })
#Html.Raw(TempData["msg"])
Every get or post controller function should return a view model, that can be used by the view to display whatever is relevant. Rather than using TempData, do something like this
class ExportJiraViewModel
{
public string Message {get;set;}
}
public IActionResult ExportJira()
{
var vm = new ExportJiraViewModel();
// fill out vm where appropriate
return View(vm);
}
Related
I am creating a API consumption tool where I have a issue in which It is giving following error when I try to call API. Please help me with this. I am trying to get CSV file and converted to TXT format with this API.
System.Runtime.CompilerServices.AsyncTaskMethodBuilder1+AsyncStateMachineBox1[System.String,StarRezToolApp.Program+d__2]
public static void GetReportInformation(string file_path_1, string Filename)
{
Utility.Utility.Log("TestFIle Reached");
var report_data = HTTP_GET();
Console.WriteLine(report_data.ToString());
var sb_csv = new StringBuilder();
try
{
if (File.Exists(file_path_1 + Filename))
{
using (StreamWriter apiresponse = File.AppendText(file_path_1 + Filename))
{
apiresponse.Write(report_data.ToString());
apiresponse.WriteLine();
}
}
else
{
using (StreamWriter apiresponse = new StreamWriter(file_path_1 + Filename))
{
apiresponse.Write(report_data.ToString());
apiresponse.WriteLine();
}
}
Utility.Utility.Log("File Created Successfully.");
}
catch (Exception ex)
{
Utility.Utility.Log("Error: Could Not Convert. Original error: " + ex.Message);
}
}
I have been calling the following method for other Information
private static async Task<string> HTTP_GET()
{
var TARGETURL = Properties.Resources.URL + Properties.Resources.Report_Name;
Console.WriteLine("GET: + " + TARGETURL);
Utility.Utility.Log("GET: + " + TARGETURL);
NetworkCredential credentials = new NetworkCredential(Properties.Resources.Username, Properties.Resources.Tocken.ToString());
HttpClientHandler handler = new HttpClientHandler
{
Credentials = credentials
};
// ... Use HttpClient with handlers which has credentials
HttpClient client = new HttpClient(handler);
HttpResponseMessage response = await client.GetAsync(TARGETURL);
HttpContent content = response.Content;
// ... Check Status Code
Utility.Utility.Log("Response StatusCode: " + (int)response.StatusCode);
Console.WriteLine("Response StatusCode: " + (int)response.StatusCode);
// ... Read the string.
string result = await content.ReadAsStringAsync();
// ... Display the result.
if (result != null && result.Length >= 50)
{
Utility.Utility.Log("Response message: Successful");
return result.ToString();
}
else
{
Utility.Utility.Log("Response message: " + response.Content);
return null;
}
}
Thank you Mr. #RuardvanElburg. I got the solution by your help.
My controller method GetReportInformationAsync needs to await for response to get out.
I have to authenticate and then request a Web Api in asp.net. The authentication is completed properly. But when I pass the session values to a new request to generate a certain response, the response returns an Controller not found error. I am trying to implement it in Asp.Net MVC application.
Here is the code for the main Index:
public async Task<ActionResult> Index()
{
var result = "";
string json = " { \"username\": \"webservice\", \"password\": \"iIU2piH6wpBF92T\" }";
var request = (HttpWebRequest)WebRequest.Create("https://os.mcparcel.com/osapi/user/login.json");
request.Method = "POST";
request.UserAgent = "MCParcel Plugin";
request.ContentType = "application/json";
using (var s = request.GetRequestStream())
{
using (var stw = new StreamWriter(s))
{
stw.Write(json);
}
}
try
{
var response = (HttpWebResponse)request.GetResponse();
var data = new StreamReader(response.GetResponseStream());
result = data.ReadToEnd();//<-this gives the value for session id and name
string key = "WucHEwRuy7trUDE7u3agEqEWrUkajuCr";
string order_id = "MCParcel3";
int labels_number = 1;
var r = await Test(key, order_id, labels_number, result);
}
catch (WebException ex)
{
var errorData = new StreamReader(ex.Response.GetResponseStream());
var errorString = errorData.ReadToEnd();
}
return View();
}
Here are the other functions inside the same controller, the error is in:
var response
public static async Task<string> Test(string key, string order_id, int labels_number, dynamic results, int? shipment_id = 0)
{
var r = await GetShippingOptionRequest(key, order_id, labels_number, results);
Console.WriteLine(r);
return r;
}
public static async Task<string> GetShippingOptionRequest(string key, string order_id, int labels_number, dynamic results, int? shipment_id = 0)
{
string json = " { \"key\": \"" + key + "\", \"order_id\": \"" + order_id + "\", \"labels_no\": " + labels_number + ", \"shipment_id\": " + shipment_id + "";
var dynObj = JsonConvert.DeserializeObject<LoginResponse>(results);
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Add("Method", "POST");
client.DefaultRequestHeaders.Add("ContentType", "application/json");
client.DefaultRequestHeaders.Add("UserAgent", "MCParcel Plugin");
client.DefaultRequestHeaders.Add("sessid", dynObj.sessid);
client.DefaultRequestHeaders.Add("session_name", dynObj.session_name);
client.DefaultRequestHeaders.Add("key", key);
client.DefaultRequestHeaders.Add("order_id", order_id);
client.DefaultRequestHeaders.Add("labels_number", Convert.ToString(labels_number));
client.DefaultRequestHeaders.Add("shipment_id", Convert.ToString(shipment_id));
//the code below is the required response that is not returning values and returning 404 error
var response = await client.GetStringAsync("https://os.mcparcel.com/osapi/service_os_api/get_label_info.json");
return response;
}
}
The response should return something similar to following:
{
"source_labels": ["https://os.mcparcel.com/sites/os.mcparcel.com/files/sourcepdflabels/labels_8c1e3033a8d23c632006639f39ef6964.pdf"],
"tracks": ["https://os.mcparcel.com/track_and_trace/(J)JD0000900581338100135004"],
"labels_file": "https://os.mcparcel.com/sites/os.mcparcel.com/files/pdf_labels/70994c37ad2a99d4047e0684c3e05c1f.pdf"
}
Any help will be highly appreciated. Thanks in advance!!!
Are you able to hit other controllers? If yes, then you might try to create another controller and start moving your current code with simple json request and build it up to complex json request. Or it might also be your routing.
If no, then it might be you have not setup config.MapHttpAttributeRoutes().
I am developing application using .net MVC C#. I tried to call rest API of PayPal for save credit card details, my code were working fine but suddenly it starting through 400 Bad Request exception. here is my code,
private static async Task<string> StorePaymentCards(string accessToken, PaymentInfoModel cardDetails)
{
try
{
var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://api.sandbox.paypal.com/v1/vault/credit-card");
var result = "";
httpWebRequest.ContentType = "application/json; charset=utf-8";
httpWebRequest.Method = "POST";
httpWebRequest.Accept = "application/json; charset=utf-8";
httpWebRequest.Headers.Add("Authorization", "Bearer " + accessToken);
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
var loginjson = new JavaScriptSerializer().Serialize(new
{
payer_id = cardDetails.PayerId.Trim(),
type = cardDetails.CardType.Trim(),
number = cardDetails.CardNumber.Trim(),
expire_month = cardDetails.ExpireMonth.Trim(),
expire_year = cardDetails.ExpireYear.Trim(),
first_name = cardDetails.FirstName.Trim()
});
streamWriter.Write(loginjson);
streamWriter.Flush();
streamWriter.Close();
//The code fails when creating the Response here, and go into catch block
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
result = streamReader.ReadToEnd();
}
return result;
}
}
catch (Exception ex)
{
return ex.GetBaseException().Message;
}
}
}
Can anyone help me out from this error?
Thank you in advance.
private static async Task<string> StorePaymentCards(string accessToken, PaymentInfoModel cardDetails)
{
try
{
//my stuff
}
catch (WebException ex)
{
string text = null;
using (WebResponse response = ex.Response)
{
HttpWebResponse httpResponse = (HttpWebResponse)response;
Console.WriteLine("Error code: {0}", httpResponse.StatusCode);
using (Stream data = response.GetResponseStream())
using (var reader = new StreamReader(data))
{
text = reader.ReadToEnd();
Console.WriteLine(text);
}
}
return text; //ex.GetBaseException().Message;
}
}
This is changed I have done in my catch block to trace proper error, so it return me that error which I was facing.
i m testing authorize.net payments and it is working fine on local host payment processing is all good. but when i upload it to my live site with test accounts i get error with
**Object reference not set to an instance of an object. at Billing.readHtmlPage(String url)**
string[] authorizeServer = readHtmlPage("https://test.authorize.net/gateway/transact.dll").Split('|');
//Error is Here
if (authorizeServer[0].ToLower() == "approved" || authorizeServer[0].ToLower() == "1")
{
//Process Payment
}
private String readHtmlPage(string url)
{
String result = "";
//Test Account ID
String strPost =
"x_login=xxxxx"&x_type=AUTH_CAPTURE&x_method=CC&x_tran_key=xxxxx&x_relay_response=&FALSE&" + "x_card_num=" + ccNum.Text + "&x_exp_date=" + ddl_CCM.SelectedValue + "/" +
ddl_CCY.SelectedValue +
"&x_amount=" + lbl_Gtotal.Text +
"&x_first_name=" + ccFName.Text + "&x_last_name=" + ccLName.Text +
"&x_address=" + Server.UrlEncode(hf_street.Value) + "&x_city=" +
hf_city.Value +
"&x_state=" + hf_state.Value + "&x_zip=" + hf_zip.Value;
StreamWriter myWriter = null;
HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create(url);
objRequest.Method = "POST";
objRequest.ContentLength = strPost.Length;
objRequest.ContentType = "application/x-www-form-urlencoded";
try
{
myWriter = new StreamWriter(objRequest.GetRequestStream());
myWriter.Write(strPost);
}
catch (Exception e)
{
return e.Message;
}
finally
{
myWriter.Close();
}
HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse();
using (StreamReader sr =
new StreamReader(objResponse.GetResponseStream()))
{
result = sr.ReadToEnd();
sr.Close();
}
return result;
}
Any Help would be nice and much helpful thanks
I created a Rest Webservice with ASP.NET MVC 4 and in my Webservice I'm calling a delegater which is called MessageInformer.
public MessageRepository repository = new MessageRepository();
public HttpResponseMessage PostMessage([FromBody]CoreMessage item)
{
bool status = repository.TransmitMessage(item);
if (status == true)
{
return Request.CreateResponse<bool>(HttpStatusCode.OK, status);
}
else
{
return Request.CreateResponse<bool>(HttpStatusCode.BadRequest, status);
}
}
public class MessageRepository : IMessageRepository
{
public static MessageInformer Informer;
public void SetDelegater(MessageInformer i)
{
Informer = i;
}
public bool TransmitMessage(CoreMessage item)
{
Informer(item);
return true;
}
}
When I start running the program I set a value to the delegater
MessageRepository mr = new MessageRepository();
mr.SetDelegater(informer);
that it should call the function New_MessageReceived and in the debug mode I see that the delegater has the right value after declaring it but when I call the Rest client after starting the program and it's comming to the function TransmitMessage(CoreMessage item) the delegater Informer is null although I assigned a value to it before. I set some breakpoints and it's never entering the function or the delegater between the starting and the web request so I don't have any idea why my delegater is null.
Rest client
try
{
url = "http://localhost:5089/api/message";
method = "POST";
string messageString = JsonConvert.SerializeObject(message);
var request = (HttpWebRequest)WebRequest.Create(url);
request.Method = method;
request.ContentType = "application/json; chatset=utf-8";
using (Stream requestStream = request.GetRequestStream())
using (StreamWriter writer = new StreamWriter(requestStream, Encoding.UTF8))
{
writer.Write(messageString);
}
var response = request.GetResponse() as HttpWebResponse;
if (request.HaveResponse == true && response == null)
{
String msg = "response was not returned or is null";
throw new WebException(msg);
}
if (response.StatusCode != HttpStatusCode.OK)
{
String msg = "response with status: " + response.StatusCode + " " + response.StatusDescription;
throw new WebException(msg);
}
// check response headers for the content type
string contentType = response.GetResponseHeader("Content-Type");
// get the response content
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
string responseText = reader.ReadToEnd();
reader.Close();
Console.WriteLine("Received " + messageString);
}
catch (Exception ex)
{
reponseAsString += "ERROR: " + ex.Message;
}
this
public MessageRepository repository = new MessageRepository();
not that
MessageRepository mr = new MessageRepository();
mr.SetDelegater(informer);
You should make sure repository is initialized properly (did you forget to assign mr to <object>.repository?).