C# .net Core web Api Get request # parameter - c#

I use authorization via oauth.vk.com Docs here
When I call on web-browser
https://oauth.vk.com/authorize?client_id=1&display=page&redirect_uri=http://example.com/callback&scope=friends&response_type=token&v=5.80
After I sign in to vk.com and accept permissions to my server vk.com send Get request like this:
http://example.com/callback#access_token=c9186f0de67865740b9bd920a67320142434422007d16cf79031734fd450657cd4ba221106ce7232e74b7&expires_in=86400&user_id=1&email=example#mail.com
I don't know how to take #access_token in my Get method
Parameters with ? like expires_in, user_id and email I can take like this
[Route("vkauth")]
public class VKAuthController : Controller {
[HttpGet]
public string Get_VkAuth([FromQuery] string access_token, string expires_in, string user_id, string email) {
}
But how to take parameter #access_token?

Just use the HttpRequestMessage in the function and extract the token via the header (if the token is send using headers: Authorization)
For eg:
public string Get_VkAuth(HttpRequestMessage request,[FromQuery] string access_token, string expires_in, string user_id, string email) {
String access_token= request.Headers.Authorization.ToString();
}

correct Answer in comment by camilo-terevinto
Nothing after the # reaches the server. You are attempting to use a a
client-side implementation in server-side code. That's the first
signal you are not doing it correctly

Related

How can I make a return with parameters in a View c# asp .net mvc?

Sorry for the title, but don't know how to explain it. (.NET ASP MVC)
So what I'm trying is to create a payment request via TripleA API(redirect on their page), if the payment is successful, they will redirect on my success page with some parameters, how can I handle those parameters?
What I've tried:
public IActionResult ErrorPage(string payment_reference, string status)
{
return View(payment_reference,status);
}
https://developers.triple-a.io/docs/triplea-api-doc/dd286311a5afc-make-a-payment-request
(scroll down to success_url for more info)
To expand on Steve's comment, create a record (less code than a class) as follows...
public record ErrorViewModel(string PaymentReference, string Status);
...then use this when you send data to the view...
public IActionResult ErrorPage(string payment_reference, string status)
{
return View(new ErrorViewModel(payment_reference,status));
}
You'll need to update your view to have the following line at the top...
#model ErrorViewModel
That should be all you need.
Based on the documentation, you expect a request like this,
https://www.myshop.com/payment-success?status=paid&payment_reference=ASDDF...&order_currency=USD&order_amount=10
And you translate that into a controller method,
[HttpGet("payment-success")]
public IActionResult ResultPage(string payment_reference, string status, string order_currency, decimal order_amount)
{
var result = new ResultViewModel(payment_reference,status, order_currency, order_amount);
return View(result);
}
I also noticed that the doc says,
Note: This field is required if integrating using External URL Payment Form. For other integrations, either insert the field with a url, or remove the field completely.
So if you use External URL Payment Form integration, then I don't think you will be able to get the status and reference.
The same applies for cancel_url.

Post Special Characters to web API from angular application

API post method is as show below,
[HttpPost]
public HttpResponseMessage CreateTemplate([FromUri]string templateName)
{
//Code...
}
and Angular post method is as show below,
CreateTemplate(templateName: string): Observable<any> {
return this.httpClient.post<any>(Url + "Templates/CreateTemplate?templateName=" + templateName, "");
}
How can I send the special characters to web API? If I try to send special characters, I will end up with receiving null in Web API.
The # indicates a fragment, it and everything after it doesn't get sent to the server.
Given you use it as a query string parameter, you need to percent-encode it:
templateName=" + encudeURIcomponent(templateName)
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent

How to correctly get access token in ShopifySharp .Net library?

I use https://github.com/nozzlegear/ShopifySharp .Net library to work with Shopify Api. I just create dev webshop and I want to test some GET methods. In documentation I saw next code:
string code = Request.QueryString["code"];
string myShopifyUrl = Request.QueryString["shop"];
string accessToken = await AuthorizationService.Authorize(code, myShopifyUrl, shopifyApiKey, shopifySecretKey);
All parameters I understand except first , what code is this , where I should get it?? Thanks
This is basically Authorization code
It is with respect to concept of "OAuth"
Refer:
https://help.shopify.com/api/getting-started/authentication/oauth
You should create a method in your controller which will receive a callback from Shopify:
public ActionResult Callback(string code, string shop) {
string accessToken = await AuthorizationService.Authorize(code, myShopifyUrl, shopifyApiKey, shopifySecretKey);
}
Then when you building authorization URL, you should set variable redirectUrl to the method above:
//This is the user's store URL.
string usersMyShopifyUrl = "https://example.myshopify.com";
// A URL to redirect the user to after they've confirmed app installation.
// This URL is required, and must be listed in your app's settings in your Shopify app dashboard.
// It's case-sensitive too!
string redirectUrl = "https://example.com/my/redirect/url";
//An array of the Shopify access scopes your application needs to run.
var scopes = new List<AuthorizationScope>()
{
AuthorizationScope.ReadCustomers,
AuthorizationScope.WriteCustomers
};
//Or, use an array of string permissions
var scopes = new List<string>()
{
"read_customers",
"write_customers"
}
//All AuthorizationService methods are static.
string authUrl = AuthorizationService.BuildAuthorizationUrl(scopes, usersMyShopifyUrl, shopifyApiKey, redirectUrl);
And once user will be redirected to authorization URL, it will open Shopify page where user will be able to install app. Then Shopify will redirect him to your callback method with code and shop parameters

Postman Testing send string to Web Api accepting string is null

I have been testing all the Get,Create,Update methods with Postman in which the Get passes in nothing. The Create and Update passes in raw json with Activity object with several properties that do match up with the C# class
So this signature for Create and Update works fine
[HttpPost]
public IHttpActionResult UpdateActivity(Activity activity)
Above works with Postman passing in JSON content type with all the properties. I have done this on OTHER projects.
HOWEVER
I'm trying to simply pass in a string and it is null no matter what
public IHttpActionResult DeleteActivity([FromBody]string Id)
{
// delete
var del = ActivityService.DeleteActivity(Id);
return Ok(del);
}
Postman I tried MANY ways
http://localhost:49810/api/activityapi/deleteactivity
I have tried MANY many ways based on blogs and google search one such example
{ "Id" = "5808786fa3e9ec79546b3c71" }
I know this is an older question but I wanted to help those who might have a similar problem as I was able to get this working.
In WebAPI Controller my method is setup as
[HttpPost]
public IHttpActionResult Create([FromBody] int eventId)
{
....
}
In order to get this to test properly in Postman you have to: In body, set to raw, make sure JSON (application/json) is set and then just add value like 2 that's it.. not like { "eventId":2 } which is proper JSON just the value and then it will work.
So in original poster's case, in Postman, if you set Body to raw, JSON (application/json) then "5808786fa3e9ec79546b3c71" as value it will work.
In Postman ensure the body is set to raw and select json and in the body just write "your string" in quotes. Do not use {} to surround it because that is to make a complex object
Try the following in the body, with the content-type as application/json
{ "5808786fa3e9ec79546b3c71" }
As when you specify it like so, it will attempt to de-serialize into a complex type with a property of Id
{ "Id" : "5808786fa3e9ec79546b3c71" }
Old question, but for those still wondering, I would recommend sending your string as a query parameter. Take a method like this for example:
[AllowAnonymous]
[HttpGet("resendEmailConfirmtionLink")]
public async Task<IActionResult> ResendEmailConfirmationLink(string email)
{
var user = await _userManager.FindByEmailAsync(email);
if (user == null) return Unauthorized();
var origin = Request.Headers["origin"];
var token = await _userManager.GenerateEmailConfirmationTokenAsync(user);
token = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(token));
var verifyUrl = $"{origin}/verifyEmail?token={token}&email={user.Email}";
var message = $"<p>Please click the below link to verify your email address:</p><p><a href='{verifyUrl}'>Click to verify email</a></p>";
await _emailSender.SendEmailAsync(user.Email, "Please verify email", message);
return Ok("Email verification link resent");
}
This method expects a key value pair of a string called email. You can send your request like "http://localhost:5000/api/account/verifyEmail?email=myemail#test.com" or, in Postman, add it as a parameter like this:
postman query params
Your payload is not valid.
Change-->
{ "Id" = "5808786fa3e9ec79546b3c71" }
To-->
{ "Id" : "5808786fa3e9ec79546b3c71" }
[HttpPost]
public IHttpActionResult Create(int eventId)
{
....
}
Use form-data instead of raw-json
Key - eventId
Value - "5808786fa3e9ec79546b3c71"
This worked for me.

ASP.NET Web Api - multiple params 500 error

' trying to make an web api controller with two parameters: one model object and string.
public string AddDevice(Device device, [FromBody] string userName)
{
// Some operations here
}
When I try it with one parameter on fiddler:
For Device object (body request):
{
"DeviceName":"name,
"StolenFlag":false
}
For string "[FromBody] string userName" (body request):
"userName"
It works fine. I just do not know how to make this method works with those two parameters. When I try connecting request body on fiddler like that:
{
"DeviceName":"name,
"StolenFlag":false
}
"userName"
I get an 500 error. It means, that server finds correct controller method but can't handle request. Any ideas?
First add the following line to WebApiConfig.cs in your App_Start folder.
GlobalConfiguration.Configuration.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;
It goes inside this function:
public static void Register(HttpConfiguration config)
Build your API and read the full error message from the Response. This should tell you exactly what's happening.
Since you can have only one parameter in the Request body you can change the method to accept username in the URI.
public string AddDevice([FromBody] Device device, string userName)
{
// Some operations here
return "";
}

Categories

Resources