I am trying to validate an email whether it is real or fake. I am using some code but it always returns Ok.
This is my code:
public string validateEmail(string userEmail)
{
try
{
string key = "xxxx";
string email = "xxxx";
var crmUrl = "https://app.emaillistvalidation.com/api/verifEmail?secret=" + key + "&email=" + email;
string url = crmUrl;
var client = new RestClient(url);
client.RemoteCertificateValidationCallback = new RemoteCertificateValidationCallback((sender, certificate, chain, policyErrors) => { return true; });
var request = new RestRequest();
request.AddHeader("authorization", "Basic xxxxxxxxxxxxxxxxxx");
IRestResponse response = client.Execute(request);
var content = response.Content;
return content;
}
catch (Exception ex)
{
}
return default;
}
What is wrong here? And what can I do instead?
I am trying to validate an email whether it is real or fake. I am
using some code but it always returns Ok.
I have gone through the code and the API you have shared. I also register and open a demo api on https://app.emaillistvalidation.com/api and it's behaving as expected for both valid and invalid email. Here are my steps:
Register on app.emaillistvalidation.com
My Controller Code
[Route("ValidateEmail")]
[HttpGet]
public async Task<IActionResult> ValidateEmail(string emailId)
{
var handler = new HttpClientHandler();
var data = "";
handler.ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) => { return true; };
var client = new HttpClient(handler);
client.DefaultRequestHeaders.Accept.Clear();
var responseFromApi = await client.GetAsync("https://app.emaillistvalidation.com/api/verifEmail?secret=" + apiSecret + "&email=" + emailId + "");
if (responseFromApi.IsSuccessStatusCode)
{
data = await responseFromApi.Content.ReadAsStringAsync();
}
return Ok(data);
}
Output For Valid & Invalid Email
Postman Direct Test
I have also tested on Postman for valid email I got ok response and for invalid and wrong email I got unknown and disable response:
Valid Email:
Wrong Email:
Wrong Domain:
Note: Please double-check the way you are trying. You could have a look on my code and the way I have tested. It's working as expected which has been shared in the screenshots
Related
Just started at a new company and we all use Jira, the customers are determined to not use it as they don't like it so I have decided to build a simple Windows Form when they can both Log tickets and get Updates and Comments in a nice simple UI.
Now I have never done any coding before 2 weeks ago so it has been a struggle to get my head around both C# and Rest (Have made scripts for basic IT fixes but never anything as complex as this!)
Back onto point, Set up and got a Rest API set up with a Rest Client but everytime I try pull data from a ticket on Jira I get the error:
{"errorMessages":["You do not have the permission to see the specified issue.","Login Required"],"errors":{}}
Here is the code from the Form:
private void button3_Click_1(object sender, EventArgs e)
{
var client = new RestClient("https://jira.eandl.co.uk/rest/api/2/issue/ITREQ-" + textBox1.Text
);
client.Authenticator = new SimpleAuthenticator("username", "abc", "password", "123");
var request = new RestRequest(Method.GET);
request.AddParameter("token", "saga001", ParameterType.UrlSegment);
// request.AddUrlSegment("token", "saga001");
request.OnBeforeDeserialization = resp => { resp.ContentType = "application/json"; };
var queryResult = client.Execute(request);
Console.WriteLine(queryResult.Content);
}
And here is the code from the Rest Client itself:
public Restclient()
{
endPoint = string.Empty;
httpMethod = httpVerb.GET;
}
private string logonAttempt;
public string makeRequest()
{
string strResponseValue = string.Empty;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(endPoint);
request.Method = httpMethod.ToString();
String authHeader = System.Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(userName + ":" + userPassword));
request.Headers.Add("Authorization", authType.ToString() + " " + authHeader);
HttpWebResponse response = null;
try
{
response = (HttpWebResponse)request.GetResponse();
//Process the Response Stream... (Could be JSON, XML ot HTML etc...)
using (Stream responseStream = response.GetResponseStream())
{
if (responseStream != null)
{
using (StreamReader reader = new StreamReader(responseStream))
{
strResponseValue = reader.ReadToEnd();
}//End of Stream Reader
}
}//end of Response Stream
}
catch (Exception ex)
{
strResponseValue = "(\"errorMessages\":[\"" + ex.Message.ToString() + "\"],\"errors\":{}}";
}
finally
{
if(response != null)
{
((IDisposable)response).Dispose();
}
}
return strResponseValue;
}
}
}
Now obviously I am expecting that I have missed something absolutely bigginer as like I said, I've never taken on a project like this before and had 0 experience.
Just looking for someone to bluntly tell me what I'm doing wrong
Changed to this as per answer:
private void button3_Click_1(object sender, EventArgs e)
{
var client = new
RestClient("https://jira.eandl.co.uk/rest/api/2/issue/ITREQ-" + textBox1.Text
);
client.Authenticator = new HttpBasicAuthenticator("username", "password");
var request = new RestRequest(Method.GET);
string authHeader = Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes("cdale!" + ":" + "Chantelle95!"));
request.AddHeader("Authorization", "Basic " + authHeader);
request.OnBeforeDeserialization = resp => { resp.ContentType = "application/json"; };
var queryResult = client.Execute(request);
Console.WriteLine(queryResult.Content);
}
By default with the Jira REST API, you can use Basic Authentication or OAuth2. I think that more easy way for you will be to use the Basic one.
I'm not sure why you have a class where you define your custom RestClient since the first block of code uses the RestSharp one from http://restsharp.org.
In this case, you will need to modify your authenticator:
client.Authenticator = new HttpBasicAuthenticator(userName, password);
And I think that you should remove the line where you specify a token. I don't think that it's required.
Finally, the class Restclient doesn't seem to be used, then remove it.
You could also uses what you have created in your custom RestClient and manually specify a Basic header:
string authHeader = Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes(userName + ":" + userPassword));
request.AddHeader("Authorization", "Basic " + authHeader);
However, it's essentially the behavior of the HttpBasicAuthenticator class.
If you don't want to encode your credentials in every request here is how to do it using cookies.
When requesting the cookie you don't need to add any authorization on the headers. This method will accept a JSON string with the user name and password and the URL. It will return the cookie values.
public async Task<JiraCookie> GetCookieAsync(string myJsonUserNamePassword, string JiraCookieEndpointUrl)
{
using (var client = new HttpClient())
{
var response = await client.PostAsync(
JiraCookieEndpointUrl,
new StringContent(myJsonUserNamePassword, Encoding.UTF8, "application/json"));
var json = response.Content.ReadAsStringAsync().Result;
var jiraCookie= JsonConvert.DeserializeObject<JiraCookie>(json);
return jArr;
}
}
public class JiraCookie
{
public Session session { get; set; }
}
public class Session
{
public string name { get; set; }
public string value { get; set; }
}
When I call it using url: http://[baseJiraUrl]/rest/auth/1/session it returns the following JSON response:
{
"session" : -{
"name" : JSESSIONID,
"value" : cookieValue
}
Keep in mind the URL above is valid in the version of JIRA I'm using and may vary depending on which version you're using. Read the JIRA API documentation for the correct URL for the version you are using. I'm using the following:
https://docs.atlassian.com/software/jira/docs/api/REST/7.6.1/#auth/1/session
Remember you'll have to store your cookie and use it on every subsequent request.
Check out this answer on how add cookies to your HttpClient request: How do I set a cookie on HttpClient's HttpRequestMessage.
Once you're done with the cookie (logging out) simply send a delete http request with the same URL as the post.
Reference: https://stackoverflow.com/a/49109192/7763903
I am trying to implement Mail Chimp's new API with my ASP.NET C# website so when a user enters their email address into an input box it will be added to my mailchimp list automatically. I have tried various other methods however none of these have worked.
I have tried a Web Client which threw a 405 Cannot use that Method response and a HttpClient which threw an error on the starred GetStringAsync method call because its not a task.
My code so far is detailed below:
public bool BatchSubscribe(IEnumerable<MailChimpSubscriberModel> newSubscribers)
{
if (string.IsNullOrEmpty(_defaultListId)) throw new ArgumentNullException(Res.Resource.MailChimpIntegrationNoListId);
if (string.IsNullOrEmpty(_apiKey)) throw new ArgumentNullException(Res.Resource.MailChimpIntegrationNoApiKey);
foreach (MailChimpSubscriberModel subscriber in newSubscribers)
{
string url = "https://" + _dataPoint + ".api.mailchimp.com/3.0/lists/" + _defaultListId + "/";
Subscriber member = new Subscriber();
member.email = subscriber.Email;
member.subscribed = "subscribed";
string jsonString = new JavaScriptSerializer().Serialize(member);
//using (WebClient client = new WebClient())
//{
// client.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
// client.Headers[HttpRequestHeader.Authorization] = new AuthenticationHeaderValue("Basic", _apiKey).ToString();
// string HtmlResult = client.(url, jsonString);
// return true;
//}
using (var http = new HttpClient())
{
http.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Basic", _apiKey);
string content = await http.**GetStringAsync**(#"https://us11.api.mailchimp.com/3.0/lists");
Console.WriteLine(content);
}
}
return false;
}
I'm a bit late to this question, but as it took me half a day to figure it out, here there is my answer, so it can help others. I'm using MailChimp 3.0:
private void subscribeAddress()
{
string apiKey = "APIKEY-usX"; //your API KEY created by you.
string dataCenter = "usX";
string listID = "listID"; //The ListID of the list you want to use.
SubscribeClassCreatedByMe subscribeRequest = new SubscribeClassCreatedByMe
{
email_address = "somebodys#email.com",
status = "subscribed"
};
subscribeRequest.merge_fields = new MergeFieldClassCreatedByMe();
subscribeRequest.merge_fields.FNAME = "YourName";
subscribeRequest.merge_fields.LNAME = "YourSurname";
using (HttpClient client = new HttpClient())
{
var uri = "https://" + dataCenter + ".api.mailchimp.com/";
var endpoint = "3.0/lists/" + listID + "/members";
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", apiKey);
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
client.BaseAddress = new Uri(uri);
//NOTE: To avoid the method being 'async' we access to '.Result'
HttpResponseMessage response = client.PostAsJsonAsync(endpoint, subscribeRequest).Result;//PostAsJsonAsync method serializes an object to
//JSON and then sends the JSON payload in a POST request
//StatusCode == 200
// -> Status == "subscribed" -> Is on the list now
// -> Status == "unsubscribed" -> this address used to be on the list, but is not anymore
// -> Status == "pending" -> This address requested to be added with double-opt-in but hasn't confirmed yet
// -> Status == "cleaned" -> This address bounced and has been removed from the list
//StatusCode == 404
if ((response.IsSuccessStatusCode))
{
//Your code here
}
}
}
Here there are the classes SubscribeClassCreatedByMe and MergeFieldClassCreatedByMe
namespace Subscriber
{
public class SubscribeClassCreatedByMe
{
public string email_address { get; set; }
public string status { get; set; }
public MergeFieldClassCreatedByMe merge_fields { get; set; }
}
}
namespace Subscriber
{
public class MergeFieldClassCreatedByMe
{
public string FNAME { get; set; }
public string LNAME { get; set; }
}
}
Well, I hope this help!!
401 isn't "cannot use that method" it's "Unauthorized". You've got an authentication error. From the looks of things, you're not quite doing basic auth the right way. Check out this example for the details you're missing.
PS: the response that comes back from APIv3 is usually pretty helpful, so you should always make sure to look at that whole response, not just the status code.
It works if you change auth to these lines:
String username = "abc"; //anything
String password = apiKey; //your apikey
String encoded = Convert.ToBase64String(Encoding.GetEncoding("ISO-8859-1").GetBytes(username + ":" + password));
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", encoded);
Below code snippet is should work on .NET Core 2.1 using Mailchimp API V3.0:
string url = #"https://" + mailchimpInstance + ".api.mailchimp.com/3.0/lists/" + ListId + "/members";
var info = new Info() { email_address = "example#gmail.com", status = "subscribed" };
var infoJson = JsonConvert.SerializeObject(info);
using (var client = new HttpClient())
{
var uri = "https://" + mailchimpInstance + ".api.mailchimp.com/";
var endpoint = "3.0/lists/" + ListId + "/members";
try
{
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic",ApiKey);
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
client.BaseAddress = new Uri(uri);
var content = new StringContent(infoJson.ToString(), Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.PostAsync(endpoint, content);
var responseString = await response.Content.ReadAsStringAsync();
Console.WriteLine("Response from server -> " + responseString);
return Ok();
Add into References MailChimp.Net.dll
than you can define an interface like
IMailChimpManager manager = new MailChimpManager(ConfigurationManager.AppSettings["MailChimpApiKey"].ToString());
than you can add or update your client in your MailChimp list
Member m = await manager.Members.AddOrUpdateAsync(ConfigurationManager.AppSettings["MailChimpListId"].ToString(), new Member { EmailAddress = _email, EmailType = "html", Status = Status.Pending});
m = await manager.Members.AddOrUpdateAsync(ConfigurationManager.AppSettings["MailChimpListId"].ToString(), new Member { EmailAddress = _email, EmailType = "html", Status = Status.Subscribed });
It is very simple.. I think...
I'm trying to call Paypal api from my code. I set up the sandbox account and it works when I use curl but my code isn't working the same way, returning 401 Unauthorized instead.
Here's the curl command as documented by Paypal
curl https://api.sandbox.paypal.com/v1/oauth2/token -H "Accept: application/json" -H "Accept-Language: en_US" -u "A****:E****" -d "grant_type=client_credentials"
UPDATE: Apparently the .Credentials doesn't do the trick, instead setting Authorization header manually works (see code)
Here's the code (trimmed to its essence):
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("https://api.sandbox.paypal.com/v1/oauth2/token");
request.Method = "POST";
request.Accept = "application/json";
request.Headers.Add("Accept-Language:en_US")
// this doesn't work:
**request.Credentials = new NetworkCredential("A****", "E****");**
// DO THIS INSTEAD
**string authInfo = Convert.ToBase64String(System.Text.Encoding.Default.GetBytes("A****:E****"));**
**request.Headers["Authorization"] = "Basic " + authInfo;**
using (StreamWriter swt = new StreamWriter(request.GetRequestStream()))
{
swt.Write("grant_type=client_credentials");
}
request.BeginGetResponse((r) =>
{
try
{
HttpWebResponse response = request.EndGetResponse(r) as HttpWebResponse; // Exception here
....
} catch (Exception x) { .... } // log the exception - 401 Unauthorized
}, null);
This is the request from code captured by Fiddler (raw), there are no authorization parameters for some reason:
POST https://api.sandbox.paypal.com/v1/oauth2/token HTTP/1.1
Accept: application/json
Accept-Language: en_US
Host: api.sandbox.paypal.com
Content-Length: 29
Expect: 100-continue
Connection: Keep-Alive
grant_type=client_credentials
Hoping the following code help to anyone who is still looking for a good piece of cake to get connected to PayPal.
As many people, I've been investing a lot of time trying to get my PayPal token access without success, until I found the following:
public class PayPalClient
{
public async Task RequestPayPalToken()
{
// Discussion about SSL secure channel
// http://stackoverflow.com/questions/32994464/could-not-create-ssl-tls-secure-channel-despite-setting-servercertificatevalida
ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
try
{
// ClientId of your Paypal app API
string APIClientId = "**_[your_API_Client_Id]_**";
// secret key of you Paypal app API
string APISecret = "**_[your_API_secret]_**";
using (var client = new System.Net.Http.HttpClient())
{
var byteArray = Encoding.UTF8.GetBytes(APIClientId + ":" + APISecret);
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
var url = new Uri("https://api.sandbox.paypal.com/v1/oauth2/token", UriKind.Absolute);
client.DefaultRequestHeaders.IfModifiedSince = DateTime.UtcNow;
var requestParams = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("grant_type", "client_credentials")
};
var content = new FormUrlEncodedContent(requestParams);
var webresponse = await client.PostAsync(url, content);
var jsonString = await webresponse.Content.ReadAsStringAsync();
// response will deserialized using Jsonconver
var payPalTokenModel = JsonConvert.DeserializeObject<PayPalTokenModel>(jsonString);
}
}
catch (System.Exception ex)
{
//TODO: Log connection error
}
}
}
public class PayPalTokenModel
{
public string scope { get; set; }
public string nonce { get; set; }
public string access_token { get; set; }
public string token_type { get; set; }
public string app_id { get; set; }
public int expires_in { get; set; }
}
This code works pretty well for me, hoping for you too. The credits belong to Patel Harshal who posted his solution here.
This Works using HttpClient...
'RequestT' is a generic for the PayPal request arguments, however it is not used. The 'ResponseT' is used and it is the response from PayPal according to their documentation.
'PayPalConfig' class reads the clientid and secret from the web.config file using ConfigurationManager.
The thing to remember is to set the Authorization header to "Basic" NOT "Bearer" and if and to properly construct the 'StringContent' object with right media type (x-www-form-urlencoded).
//gets PayPal accessToken
public async Task<ResponseT> InvokePostAsync<RequestT, ResponseT>(RequestT request, string actionUrl)
{
ResponseT result;
// 'HTTP Basic Auth Post' <http://stackoverflow.com/questions/21066622/how-to-send-a-http-basic-auth-post>
string clientId = PayPalConfig.clientId;
string secret = PayPalConfig.clientSecret;
string oAuthCredentials = Convert.ToBase64String(Encoding.Default.GetBytes(clientId + ":" + secret));
//base uri to PayPAl 'live' or 'stage' based on 'productionMode'
string uriString = PayPalConfig.endpoint(PayPalConfig.productionMode) + actionUrl;
HttpClient client = new HttpClient();
//construct request message
var h_request = new HttpRequestMessage(HttpMethod.Post, uriString);
h_request.Headers.Authorization = new AuthenticationHeaderValue("Basic", oAuthCredentials);
h_request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
h_request.Headers.AcceptLanguage.Add(new StringWithQualityHeaderValue("en_US"));
h_request.Content = new StringContent("grant_type=client_credentials", UTF8Encoding.UTF8, "application/x-www-form-urlencoded");
try
{
HttpResponseMessage response = await client.SendAsync(h_request);
//if call failed ErrorResponse created...simple class with response properties
if (!response.IsSuccessStatusCode)
{
var error = await response.Content.ReadAsStringAsync();
ErrorResponse errResp = JsonConvert.DeserializeObject<ErrorResponse>(error);
throw new PayPalException { error_name = errResp.name, details = errResp.details, message = errResp.message };
}
var success = await response.Content.ReadAsStringAsync();
result = JsonConvert.DeserializeObject<ResponseT>(success);
}
catch (Exception)
{
throw new HttpRequestException("Request to PayPal Service failed.");
}
return result;
}
IMPORTANT: use Task.WhenAll() to ensure you have a result.
// gets access token with HttpClient call..and ensures there is a Result before continuing
// so you don't try to pass an empty or failed token.
public async Task<TokenResponse> AuthorizeAsync(TokenRequest req)
{
TokenResponse response;
try
{
var task = new PayPalHttpClient().InvokePostAsync<TokenRequest, TokenResponse>(req, req.actionUrl);
await Task.WhenAll(task);
response = task.Result;
}
catch (PayPalException ex)
{
response = new TokenResponse { access_token = "error", Error = ex };
}
return response;
}
Paypal has deprecated TLS 1.1, and only accepts 1.2 now. Unfortunately .NET (prior to version 4.7) uses 1.1 by default, unless you configure it otherwise.
You can turn on TLS 1.2 with this line. I recomend placing it Application_Start or global.asax.
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
I too suffered from a lack of example code and various issues with response errors and codes.
I am a big fan of RestClient as it helps a lot with integrations and the growing number of RESTful API calls.
I hope this small snippet of code using RestSharp helps someone: -
if (ServicePointManager.SecurityProtocol != SecurityProtocolType.Tls12) ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; // forced to modern day SSL protocols
var client = new RestClient(payPalUrl) { Encoding = Encoding.UTF8 };
var authRequest = new RestRequest("oauth2/token", Method.POST) {RequestFormat = DataFormat.Json};
client.Authenticator = new HttpBasicAuthenticator(clientId, secret);
authRequest.AddParameter("grant_type","client_credentials");
var authResponse = client.Execute(authRequest);
// You can now deserialise the response to get the token as per the answer from #ryuzaki
var payPalTokenModel = JsonConvert.DeserializeObject<PayPalTokenModel>(authResponse.Content);
I try to use FRED with Hammock to use the provided REST service. unfortunately I have no idea how to use it.
what I did so far:
string url = "http://wit.istc.cnr.it/stlab-tools/fred/api";
Hammock.RestClient client = new Hammock.RestClient();
client.AddHeader("Accept", "image/png -F text=Miles Davis was an american jazz musician");
//client.AddHeader("Accept", "text=Miles Davis was an american jazz musician");
client.Authority = url;
Hammock.RestRequest req = new Hammock.RestRequest();
req.Path = url;
Hammock.RestResponse response = client.Request(req);
string _result = client.Request(req).Content;
You're making a POST request but you never specify that.
From juniper.net, an extract to make POST Request:
public void makeQRest() {
try {
string auth = "http://wit.istc.cnr.it/stlab-tools/fred/api";
string body = "text=Miles Davis was an american jazz musician";
IWebCredentials credentials = new Hammock.Authentication.Basic.BasicAuthCredentials {
Username = Config.uName,
Password = Config.pWord
};
RestClient client = new RestClient {
Authority = auth,
};
client.AddHeader("content-type", "Accept: image/png");
RestRequest request = new RestRequest {
Credentials = credentials,
Method = WebMethod.Post
};
request.AddPostContent(Encoding.UTF8.GetBytes(body));
RestResponse response = client.Request(request);
Console.WriteLine("the create Queue status is " + response.StatusCode);
Console.WriteLine(response.Content);
Console.ReadLine();
} catch (Exception e) {
Console.WriteLine(e.Message);
Console.ReadLine();
}
}
The Method = WebMethod.Post part is the first missing thing in your code.
I am developing social networks integration for my asp.net mvc4 application.
Twitter and Facebook were very easy for me but I am seriously stuck with LinkedIn.
Here is my code.
public ActionResult LinkedInTest(string text)
{
var client = new RestClient
{
Authority = "https://api.linkedin.com/uas/oauth",
Credentials = LinkedInSocialHelper.GetCredentials()
};
var request = new RestRequest {Path = "requestToken"};
RestResponse response = client.Request(request);
token = response.Content.Split('&')[0].Split('=')[1];
tokenSecret = response.Content.Split('&')[1].Split('=')[1];
textToPost = text;
Response.Redirect("https://api.linkedin.com/uas/oauth/authorize?oauth_token=" + token + "&scope=r_basicprofile+r_emailaddress+r_network+r_contactinfo+rw_nus");
return null;
textToPost = text;
return RedirectToAction("LinkedInCallback");
}
public ActionResult LinkedInCallback()
{
verifier = Request["oauth_verifier"];
var client = new RestClient
{
Authority = "https://api.linkedin.com/uas/oauth",
Credentials = LinkedInSocialHelper.GetCredentials(token, tokenSecret, verifier),
Method = WebMethod.Post
};
var request = new RestRequest {Path = "accessToken"};
RestResponse response = client.Request(request);
token = response.Content.Split('&')[0].Split('=')[1];
tokenSecret = response.Content.Split('&')[1].Split('=')[1];
LinkedInSocialHelper.Post(textToPost, token, tokenSecret);
return RedirectToAction("Calendar");
}
public static void Post(string text, string accessToken, string accessTokenSecret)
{
var tokenManager = new TokenManager(ApiKey, ApiSecret);
tokenManager.ExpireRequestTokenAndStoreNewAccessToken(null, null, accessToken, accessTokenSecret);
var authorization = new WebOAuthAuthorization(tokenManager, UserToken);
LinkedInService service = new LinkedInService(authorization);
//var user = service.GetCurrentUser(ProfileType.Public); - IT IS GIVING ME THE SAME ERROR - Access denied
service.CreateShare(text, VisibilityCode.ConnectionsOnly);
}
Everything works fine except last thing - posting shares - I get Access to posting shares denied exception despite the fact that I generate token using all the necessary permissions:
"https://api.linkedin.com/uas/oauth/authorize?oauth_token=" + token + "&scope=r_basicprofile+r_emailaddress+r_network+r_contactinfo+rw_nus"
Hope you good guys help me.
See the last post here - it describes how to solve it
https://developer.linkedin.com/forum/permission-scope-request-token-query-not-working?page=1