Consuming webapi with two parameters - c#

Hello I am learning WebApi and got this problem. Hours of search didn't yield any solution.
I am trying to call an api passing two parameters just for testing purposes. The one on which I am getting 404 error is GetBalance(param1, param2). I have another function exposed by the Api called GetOffice(param1) with one parameter which returns 200. The 404 I am getting is for the two parameter function.
public void GetBalance(string accountNumber,int officeId)
{
using (var client = new WebClient())
{
client.Headers.Add("Content-Type:application/json");
client.Headers.Add("Accept:application/json");
client.Headers.Add("API_KEY","1234CHECK");
var result = client.DownloadString("http://localhost/api/Accounts/GetBalance/" + accountNumber + officeId ); //URI
Console.WriteLine(Environment.NewLine + result);
}
}
static void Main(string[] args)
{
ConsumeApiSync objSync = new ConsumeApiSync();
objSync.GetBalance("01-13-00000595", 1);
}
Route
RouteTable.Routes.MapHttpRoute("OfficeApi", "api/{controller}/{action}/{accountNumber}/{officeId}");
I get 404 not found error. What must be wrong? Help Appreciated. Thanks

use a view model on your Web Api controller that contains both properties. So instead of:
public HttpresponseMessage GetBalance(string accountNumber,int officeId)
{
...
}
use:
public HttpresponseMessage Post(ViewModelName model)
{
...
}
var uri = string.Concat("http://localhost/api/Accounts/GetBalance",model);

Seems like your request URI is not correct.
var uri = string.Concat("http://localhost/api/Accounts/GetBalance/", accountNumber, "/", officeId);
Try the following code.
public void GetBalance(string accountNumber,int officeId)
{
using (var client = new WebClient())
{
client.Headers.Add("Content-Type:application/json");
client.Headers.Add("Accept:application/json");
client.Headers.Add("API_KEY","1234CHECK");
var uri = string.Concat("http://localhost/api/Accounts/GetBalance/", accountNumber, "/", officeId);
var result = client.DownloadString(uri); //URI
Console.WriteLine(Environment.NewLine + result);
}
}
static void Main(string[] args)
{
ConsumeApiSync objSync = new ConsumeApiSync();
objSync.GetBalance("01-13-00000595", 1);
}

Related

Lsing API to list results in different method

The aim of the program below is to get a list of Reports built in our database and find out how many of these reports use the field NameFirst within them.
I'm able to make an API call and, at GetReports, get a list of the ReportIDs.
However, I'm unable to move forward with calling the list I created at GetReports in the next method, GetNameFirst. I was wondering if someone could please help me out with this.
For the script below, I get a red underline for the variable values. This is understandable because I didn't know where and how to tell my code to bind the list output for GetReports to the variable values in GetNameFirst.
Also, if I could get some help in finding out which reports have the field NameFirst in them once I accomplish calling the list from the first method to the second, I'd appreciate that also. I'm currently heading in the direction of using a foreach, but I'm unsure if that's the best path to take.
Main Program
namespace NameFirstSearch
{
class Program
{
static void Main(string[] args)
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
const string username = "Username";
const string password = "Password";
const string baseUrl = "https://example.com/rest/services/";
const string queryString = "query?q=Select * From Report Where LastRanDate is not null";
const string queryNameFirst = "getreport/";
var client = new HttpClient();
client.BaseAddress = new Uri(baseUrl);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var auth = Convert.ToBase64String(Encoding.Default.GetBytes(username + ":" + password));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", auth);
GetReports(client, queryString).Wait();
GetNameFirst(client, queryNameFirst).Wait();
Console.ReadLine();
}
static async Task<List<Properties>> GetReports(HttpClient client, string queryString)
{
List<Properties> result = new List<Properties>();
var response = await client.GetAsync(queryString);
// Check for a successfull result
if (response.IsSuccessStatusCode)
{
var json = await response.Content.ReadAsStringAsync();
result = JsonConvert.DeserializeObject<List<Properties>>(json);
Console.WriteLine(result.Count());
}
else
{
// Error code returned
Console.WriteLine("No records found on first method.");
}
return result;
}
static async Task GetNameFirst(HttpClient client, string queryNameFirst)
{
string reportType = "JSON";
foreach (var item in values)
{
var output = await client.GetAsync(queryNameFirst + item.ReportID + reportType);
if (output.IsSuccessStatusCode)
{
var allText = await output.Content.ReadAsStringAsync();
var fields = JsonConvert.DeserializeObject<List<NameFirst>>(allText);
}
else
{
// Error code returned
Console.WriteLine("No records found on second method.");
}
}
}
}
Class for report list
class Properties
{
public int ReportID { get; set; }
}
Class for reports' NameFirst property
class NameFirst
{
public string FirstName { get; set; }
}
I thought this was a partial code, but since you've cleared things out.
you'll need to change your code a bit
this :
GetReports(client, queryString).Wait();
do it like this :
var reportsList = GetReports(client, queryString).Result;
now, you'll need to pass the reportsList to the second method GetNameFirst which would be adjusted to this :
static async Task GetNameFirst(HttpClient client, string queryNameFirst, List<Properties> results)
{
string reportType = "JSON";
foreach (var item in results)
{
var output = await client.GetAsync(queryNameFirst + item.ReportID + reportType);
if (output.IsSuccessStatusCode)
{
var allText = await output.Content.ReadAsStringAsync();
var fields = JsonConvert.DeserializeObject<List<NameFirst>>(allText);
}
else
{
// Error code returned
Console.WriteLine("No records found on second method.");
}
}
}
with this adjustment, you'll need to adjust the call as well :
GetNameFirst(client, queryNameFirst, reportsList).Wait();

C# Response = "WaitingForActivation"

I have an asp.net website which sends a tweet on a button click event.
I am using the TwitterApi for this and have an authenticated developer account.
This function was working from September 2018 until last month, but all of a sudden it won't send the tweets on request.
The response I get now is - "Id = 1, Status = WaitingForActivation, Method = "{null}", Result = "{Not yet computed}""
After searching around, this doesn't seem like a twitter error, but an async error of some kind. I have made some minor alterations to my website in this time, but I cant see anything I have changed that would cause this issue.
The code is below.
Can any one see why this error would occur?
protected void Publish_Click(object sender, EventArgs e)
{
DataAccess.Publish();
SendEmails();
SendTweet();
Response.Redirect("OtherPage.aspx");
}
public static void SendTweet()
{
string text = DataAccess.GetText();
var twitter = new TwitterApi();
var response = twitter.Tweet(text);
}
public TwitterApi()
{
this.consumerKey = "XXX";
this.consumerKeySecret = "XXX";
this.accessToken = "XXX";
this.accessTokenSecret = "XXX";
sigHasher = new HMACSHA1(new ASCIIEncoding().GetBytes(string.Format("{0}&{1}", consumerKeySecret, accessTokenSecret)));
}
public Task<string> Tweet(string text)
{
var data = new Dictionary<string, string> {
{ "status", text },
{ "trim_user", "1" }
};
return SendRequest("statuses/update.json", data);
}
Task<string> SendRequest(string url, Dictionary<string, string> data)
{
var fullUrl = TwitterApiBaseUrl + url;
// Timestamps are in seconds since 1/1/1970.
var timestamp = (int)((DateTime.UtcNow - epochUtc).TotalSeconds);
// Add all the OAuth headers we'll need to use when constructing the hash.
data.Add("oauth_consumer_key", consumerKey);
data.Add("oauth_signature_method", "HMAC-SHA1");
data.Add("oauth_timestamp", timestamp.ToString());
data.Add("oauth_nonce", "a"); // Required, but Twitter doesn't appear to use it, so "a" will do.
data.Add("oauth_token", accessToken);
data.Add("oauth_version", "1.0");
// Generate the OAuth signature and add it to our payload.
data.Add("oauth_signature", GenerateSignature(fullUrl, data));
// Build the OAuth HTTP Header from the data.
string oAuthHeader = GenerateOAuthHeader(data);
// Build the form data (exclude OAuth stuff that's already in the header).
var formData = new FormUrlEncodedContent(data.Where(kvp => !kvp.Key.StartsWith("oauth_")));
return SendRequest(fullUrl, oAuthHeader, formData);
}
async Task<string> SendRequest(string fullUrl, string oAuthHeader, FormUrlEncodedContent formData)
{
using (var http = new HttpClient())
{
http.DefaultRequestHeaders.Add("Authorization", oAuthHeader);
var httpResp = await http.PostAsync(fullUrl, formData);
var respBody = httpResp.ToString();
return respBody;
}
}

C# Web API method returns 403 Forbidden

Solved!!! - See last edit.
In my MVC app I make calls out to a Web API service with HMAC Authentication Filterign. My Get (GetMultipleItemsRequest) works, but my Post does not. If I turn off HMAC authentication filtering all of them work. I'm not sure why the POSTS do not work, but the GETs do.
I make the GET call from my code like this (this one works):
var productsClient = new RestClient<Role>(System.Configuration.ConfigurationManager.AppSettings["WebApiUrl"],
"xxxxxxxxxxxxxxx", true);
var getManyResult = productsClient.GetMultipleItemsRequest("api/Role").Result;
I make the POST call from my code like this (this one only works when I turn off HMAC):
private RestClient<Profile> profileClient = new RestClient<Profile>(System.Configuration.ConfigurationManager.AppSettings["WebApiUrl"],
"xxxxxxxxxxxxxxx", true);
[HttpPost]
public ActionResult ProfileImport(IEnumerable<HttpPostedFileBase> files)
{
//...
var postResult = profileClient.PostRequest("api/Profile", newProfile).Result;
}
My RestClient builds like this:
public class RestClient<T> where T : class
{
//...
private void SetupClient(HttpClient client, string methodName, string apiUrl, T content = null)
{
const string secretTokenName = "SecretToken";
client.BaseAddress = new Uri(_baseAddress);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
if (_hmacSecret)
{
client.DefaultRequestHeaders.Date = DateTime.UtcNow;
var datePart = client.DefaultRequestHeaders.Date.Value.UtcDateTime.ToString(CultureInfo.InvariantCulture);
var fullUri = _baseAddress + apiUrl;
var contentMD5 = "";
if (content != null)
{
var json = new JavaScriptSerializer().Serialize(content);
contentMD5 = Hashing.GetHashMD5OfString(json); // <--- Javascript serialized version is hashed
}
var messageRepresentation =
methodName + "\n" +
contentMD5 + "\n" +
datePart + "\n" +
fullUri;
var sharedSecretValue = ConfigurationManager.AppSettings[_sharedSecretName];
var hmac = Hashing.GetHashHMACSHA256OfString(messageRepresentation, sharedSecretValue);
client.DefaultRequestHeaders.Add(secretTokenName, hmac);
}
else if (!string.IsNullOrWhiteSpace(_sharedSecretName))
{
var sharedSecretValue = ConfigurationManager.AppSettings[_sharedSecretName];
client.DefaultRequestHeaders.Add(secretTokenName, sharedSecretValue);
}
}
public async Task<T[]> GetMultipleItemsRequest(string apiUrl)
{
T[] result = null;
try
{
using (var client = new HttpClient())
{
SetupClient(client, "GET", apiUrl);
var response = await client.GetAsync(apiUrl).ConfigureAwait(false);
response.EnsureSuccessStatusCode();
await response.Content.ReadAsStringAsync().ContinueWith((Task<string> x) =>
{
if (x.IsFaulted)
throw x.Exception;
result = JsonConvert.DeserializeObject<T[]>(x.Result);
});
}
}
catch (HttpRequestException exception)
{
if (exception.Message.Contains("401 (Unauthorized)"))
{
}
else if (exception.Message.Contains("403 (Forbidden)"))
{
}
}
catch (Exception)
{
}
return result;
}
public async Task<T> PostRequest(string apiUrl, T postObject)
{
T result = null;
try
{
using (var client = new HttpClient())
{
SetupClient(client, "POST", apiUrl, postObject);
var response = await client.PostAsync(apiUrl, postObject, new JsonMediaTypeFormatter()).ConfigureAwait(false); //<--- not javascript formatted
response.EnsureSuccessStatusCode();
await response.Content.ReadAsStringAsync().ContinueWith((Task<string> x) =>
{
if (x.IsFaulted)
throw x.Exception;
result = JsonConvert.DeserializeObject<T>(x.Result);
});
}
}
catch (HttpRequestException exception)
{
if (exception.Message.Contains("401 (Unauthorized)"))
{
}
else if (exception.Message.Contains("403 (Forbidden)"))
{
}
}
catch (Exception)
{
}
return result;
}
//...
}
My Web API Controller is defined like this:
[SecretAuthenticationFilter(SharedSecretName = "xxxxxxxxxxxxxxx", HmacSecret = true)]
public class ProfileController : ApiController
{
[HttpPost]
[ResponseType(typeof(Profile))]
public IHttpActionResult PostProfile(Profile Profile)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
GuidValue = Guid.NewGuid();
Resource res = new Resource();
res.ResourceId = GuidValue;
var data23 = Resourceservices.Insert(res);
Profile.ProfileId = data23.ResourceId;
_profileservices.Insert(Profile);
return CreatedAtRoute("DefaultApi", new { id = Profile.ProfileId }, Profile);
}
}
Here is some of what SecretAuthenticationFilter does:
//now try to read the content as string
string content = actionContext.Request.Content.ReadAsStringAsync().Result;
var contentMD5 = content == "" ? "" : Hashing.GetHashMD5OfString(content); //<-- Hashing the non-JavaScriptSerialized
var datePart = "";
var requestDate = DateTime.Now.AddDays(-2);
if (actionContext.Request.Headers.Date != null)
{
requestDate = actionContext.Request.Headers.Date.Value.UtcDateTime;
datePart = requestDate.ToString(CultureInfo.InvariantCulture);
}
var methodName = actionContext.Request.Method.Method;
var fullUri = actionContext.Request.RequestUri.ToString();
var messageRepresentation =
methodName + "\n" +
contentMD5 + "\n" +
datePart + "\n" +
fullUri;
var expectedValue = Hashing.GetHashHMACSHA256OfString(messageRepresentation, sharedSecretValue);
// Are the hmacs the same, and have we received it within +/- 5 mins (sending and
// receiving servers may not have exactly the same time)
if (messageSecretValue == expectedValue
&& requestDate > DateTime.UtcNow.AddMinutes(-5)
&& requestDate < DateTime.UtcNow.AddMinutes(5))
goodRequest = true;
Any idea why HMAC doesn't work for the POST?
EDIT:
When SecretAuthenticationFilter tries to compare the HMAC sent, with what it thinks the HMAC should be they don't match. The reason is the MD5Hash of the content doesn't match the MD5Hash of the received content. The RestClient hashes the content using a JavaScriptSerializer.Serialized version of the content, but then the PostRequest passes the object as JsonMediaTypeFormatted.
These two types don't get formatted the same. For instance, the JavaScriptSerializer give's us dates like this:
\"EnteredDate\":\"\/Date(1434642998639)\/\"
The passed content has dates like this:
\"EnteredDate\":\"2015-06-18T11:56:38.6390407-04:00\"
I guess I need the hash to use the same data that's passed, so the Filter on the other end can confirm it correctly. Thoughts?
EDIT:
Found the answer, I needed to change the SetupClient code from using this line:
var json = new JavaScriptSerializer().Serialize(content);
contentMD5 = Hashing.GetHashMD5OfString(json);
To using this:
var json = JsonConvert.SerializeObject(content);
contentMD5 = Hashing.GetHashMD5OfString(json);
Now the sent content (formatted via JSON) will match the hashed content.
I was not the person who wrote this code originally. :)
Found the answer, I needed to change the SetupClient code from using this line:
var json = new JavaScriptSerializer().Serialize(content);
contentMD5 = Hashing.GetHashMD5OfString(json);
To using this:
var json = JsonConvert.SerializeObject(content);
contentMD5 = Hashing.GetHashMD5OfString(json);
Now the content used for the hash will be formatted as JSON and will match the sent content (which is also formatted via JSON).

VersionOne: query.v1 C# OAuth2 gets 401 Unauthorized error but rest-1.oauth.v1/Data/ does work

I am able to do queries using OAuth2 and this:
/rest-1.oauth.v1/Data/Story?sel=Name,Number&Accept=text/json
However I am unable to get the OAuth2 and the new query1.v1 to work against the Sumnmer2013 VersionOne. I am getting (401) Unauthorized and specified method is not supported using two different URLs.
Here is the code that includes the working /rest-1.oauth.v1 and the non-working query1.v1 and non-working query.legacy.v1. Scroll towards the bottom of the code to see the Program Main (starting point of code)
Please advise on what I am missing here.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using OAuth2Client;
namespace ExampleMemberListCSharp
{
class Defaults
{
public static string Scope = "apiv1";
//public static string EndpointUrl = "http://localhost/VersionOne.Web";
public static string EndpointUrl = "https://versionone-test.web.acme.com/summer13_demo";
public static string ApiQueryWorks = "/rest-1.oauth.v1/Data/Member?Accept=text/json";
public static string ApiQuery = "/rest-1.oauth.v1/Data/Story?sel=Name,Number&Accept=text/json";
}
static class WebClientExtensions
{
public static string DownloadStringOAuth2(this WebClient client, IStorage storage, string scope, string path)
{
var creds = storage.GetCredentials();
client.AddBearer(creds);
try
{
return client.DownloadString(path);
}
catch (WebException ex)
{
if (ex.Status == WebExceptionStatus.ProtocolError)
{
if (((HttpWebResponse)ex.Response).StatusCode != HttpStatusCode.Unauthorized)
throw;
var secrets = storage.GetSecrets();
var authclient = new AuthClient(secrets, scope);
var newcreds = authclient.refreshAuthCode(creds);
var storedcreds = storage.StoreCredentials(newcreds);
client.AddBearer(storedcreds);
return client.DownloadString(path);
}
throw;
}
}
public static string UploadStringOAuth2(this WebClient client, IStorage storage
, string scope, string path, string pinMethod, string pinQueryBody)
{
var creds = storage.GetCredentials();
client.AddBearer(creds);
client.UseDefaultCredentials = true;
try
{
return client.UploadString(path, pinMethod, pinQueryBody);
}
catch (WebException ex)
{
if (ex.Status == WebExceptionStatus.ProtocolError)
{
if (((HttpWebResponse)ex.Response).StatusCode != HttpStatusCode.Unauthorized)
throw;
var secrets = storage.GetSecrets();
var authclient = new AuthClient(secrets, scope);
var newcreds = authclient.refreshAuthCode(creds);
var storedcreds = storage.StoreCredentials(newcreds);
client.AddBearer(storedcreds);
client.UseDefaultCredentials = true;
return client.UploadString(path, pinMethod, pinQueryBody);
}
throw;
}
}
}
class AsyncProgram
{
private static async Task<string> DoRequestAsync(string path)
{
var httpclient = HttpClientFactory.WithOAuth2("apiv1");
var response = await httpclient.GetAsync(Defaults.EndpointUrl + Defaults.ApiQuery);
var body = await response.Content.ReadAsStringAsync();
return body;
}
public static int MainAsync(string[] args)
{
var t = DoRequestAsync(Defaults.EndpointUrl + Defaults.ApiQuery);
Task.WaitAll(t);
Console.WriteLine(t.Result);
return 0;
}
}
class Program
{
static void Main(string[] args)
{
IStorage storage = Storage.JsonFileStorage.Default;
using (var webclient = new WebClient())
{
// this works:
var body = webclient.DownloadStringOAuth2(storage, "apiv1", Defaults.EndpointUrl + Defaults.ApiQuery);
Console.WriteLine(body);
}
IStorage storage2 = Storage.JsonFileStorage.Default;
using (var webclient2 = new WebClient())
{
// This does NOT work. It throws an exception of (401) Unauthorized:
var body2 = webclient2.UploadStringOAuth2(storage2, "apiv1", Defaults.EndpointUrl + "/query.v1", "SEARCH", QueryBody);
// This does NOT work. It throws an exception of The remote server returned an error: (403): Forbidden."
var body3 = webclient2.UploadStringOAuth2(storage2, "apiv1", Defaults.EndpointUrl + "/query.legacy.v1", "SEARCH", QueryBody);
// These do NOT work. Specified method is not supported:
var body4 = webclient2.UploadStringOAuth2(storage2, "apiv1", Defaults.EndpointUrl + "/oauth.v1/query.legacy.v1", "SEARCH", QueryBody);
var body5 = webclient2.UploadStringOAuth2(storage2, "apiv1", Defaults.EndpointUrl + "/oauth.v1/query.legacy.v1", "SEARCH", QueryBody);
}
Console.ReadLine();
AsyncProgram.MainAsync(args);
}
public const string QueryBody = #"
from: Story
select:
- Name
";
}
}
At this time, the query.v1 endpoint requires the query-api-1.0 scope to be granted.
You'll have to add that to your scope list (it can be simply space-separated e.g. apiv1 query-api-1.0) and visit the grant URL again to authorize the permissions.
This somewhat vital piece of information doesn't seem to appear in the docs on community.versionone.com, so it looks like an update is in order.
Also, only the rest-1.oauth.v1 and query.v1 endpoints respond to OAuth2 headers at this time. A future release will see it apply to all endpoints and remove the endpoint duplication for the two types of authentication
I have had problems in the past trying to use an HTTP method other than POST to transmit the query. Security software, IIS settings, and proxies may all handle such requests in unexpected ways.

How to get actual objects from C# Web API DbSet?

I'm trying to get a list of 'recent' donuts that have been added to the box (database) since I last checked. I'm a fatty and want some delicious noms. The problem: the server is giving me JSON that is full of $ids and $refs, so my list ends up being one object, with the rest as null (because response.Content.ReadAsAsync doesn't handle the references).
Please help. I just want some straight up donut objects man. None of this $ref icing or $id filling.
My server side controller:
public class DonutController : ApiController
{
private DonutEntities db = new DonutEntities();
// GET api/PackageEvent/since/{datetime}
public IEnumerable<Donut> GetDonutsSince([FromUri] String datetime) {
List<Donut> donuts = null;
DateTime dt = DateTime.Parse(datetime);
//return db.Donuts.Where(d => d.When > dt).AsEnumerable();
String sql = #"
SELECT *
FROM Donuts
WHERE [Donuts].[When] > CAST(#datetime AS DATETIME)
";
object[] parameters = new object[] {
new SqlParameter("#datetime", DateTime.Parse(datetime).ToString(CultureInfo.InvariantCulture))
};
List<Donut> results = db.Donuts.SqlQuery(sql, parameters).ToList();
if (results.Any()) {
donuts = results;
}
return donuts.AsEnumerable();
}
}
My client side request method:
public static IEnumerable<Donut> GetDonutsSince(DateTime dt) {
HttpClient api = new HttpClient { BaseAddress = new Uri("http://localhost:55174/api/") };
api.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
String url = "Donut/since?datetime=" + dt;
HttpResponseMessage response = api.GetAsync(url).Result;
Console.WriteLine(response.Content.ReadAsStringAsync().Result);
// outputs the raw json with $ids and $refs
IEnumerable<Donut> donuts = response.Content.ReadAsAsync<IEnumerable<Donut>>().Result;
return donuts;
}
So it turns out that the solution was to use Json.NET. It handles the $id and $ref attributes, and actually creates a list populated with objects.
New client side request method:
public static IEnumerable<Donut> GetDonutsSince(DateTime dt) {
HttpClient api = new HttpClient { BaseAddress = new Uri("http://localhost:55174/api/") };
api.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
String url = "Donut/since?datetime=" + dt;
HttpResponseMessage response = api.GetAsync(url).Result;
String responseContent = response.Content.ReadAsStringAsync().Result;
IEnumerable<Donut> events = JsonConvert.DeserializeObject<IEnumerable<Donut>>(responseContent);
return donuts;
}

Categories

Resources