C# WebAPI - getting URL with parameters passed as QueryString - c#

I've been searching for this problem but non was identical to my case.
I have the following controller:
public HttpResponseMessage GetMyService(int aType, [FromUri] string streamURL)
streamURL is a parameter that gets a full URL sent by the client.
The client calls the service like that:
http://www.myservice.com/.../GetMyService/?aType=1&streamURL=http://www.client.com/?p1=100&p2=200
The problem is that at then end, I get the [FromUri] string streamURL parameter as http://www.client.com/?p1=100 without the &p2=200
This is known and reasonable, but I cannot place any encoding/decoding functionality as the URL is cut at the very beginning.
Any help would be appreciated..
THX

The client should properly URL encode the value of the streamURL query string parameter when making the request in order to conform to the HTTP protocol specification:
http://www.myservice.com/.../GetMyService/?aType=1&streamURL=http%3A%2F%2Fwww.client.com%2F%3Fp1%3D100%26p2%3D200
So basically there's nothing you could do on the server side, you should fix the client.

Related

PayU POST notification signature validation

I'm integrating PayU API service in my web (.NET MVC Core 2.1) application.
After client pays order, PayU sends notification confirmation as POST request to my api method.
Example of PayU confirmation notification.
In heareds notification placed MD5 signature.
OpenPayu-Signature:
sender=checkout;
signature=c33a38d89fb60f873c039fcec3a14743;
algorithm=MD5;
content=DOCUMENT
string incoming_signature = c33a38d89fb60f873c039fcec3a14743;
What I supposed to do to verify that notification:
Here is instruction to verify notification signature.
1.Combine the body of the incoming notification with the value of second_key(second key is avaliable in my account page in payu ):
string concatenated = JSONnotification + second_key;
2.Select an expected signature value by applying the hashing function (e.g. md5) in the received chain of characters:
string expected_signature = md5(concatenated)
3.Compare the strings: expected_signature and incoming_signature:
bool signature_is_correct = (expected_signature == incoming_signature);
Problem is checksums is not matching.
I Handle this notification in my controller method:
[HttpPost]
[AllowAnonymous]
[Route("notify")]
public IActionResult TransactionConfirm([FromBody] dynamic content)
content variable parsed as a object
and I accessing JsonBody string as content.ToString()
method.
Is it possible to hashes isn't matched because method content.ToString() can return not the same string like in request body?
Is there any ways to handle json as argument in .Net Core method? (I've already tried to placed JObject, but method ToString() also returned string that generated to hash isn't matching)
To compute a matching hash, you need to read the incoming request as is, without deserializing it. So yes, your generated JSON probably differs from the sent one (whitespace characters).
I'm not really familiar with ASP.NET Core, but in the old ASP.NET, you could read the request content using:
var json = new System.IO.StreamReader(Request.InputStream).ReadToEnd();

Read the URL parameter which is set after the hash symbol using ASP.NET Core MVC

Let's say we have a controller like this:
public class HomeController : Controller
{
[HttpGet]
public IActionResult Foo(string token)
{
return RedirectToAction(nameof(Index));
}
}
When I type the following URL address in the webbrowser:
https://localhost:44348/home/foo#dsfdsf
I would like to be able to read the dsfdsf after the hash symbol and bind it to the token variable.
Now I'm receiving null value. I'm getting such URL from the 3rd party app and I need to consume the response somehow and read the data from the query string.
I played with [FromQuery] attribute but I haven't managed it to work so far.
Any ideas?
Cheers
I have a work around for you, but first of all lets get more into the problem.
The strings after the hash symbol which are called Fragment values are not query parameters but they are strings to be read by the client-side (living in the browser) and the server cannot read them because they are not sent to the server by the browser.
Some authentication providers like Google and Azure send the access token as Fragment value for security reasons so that they are not transferred over the internet after they get sent as direct response from the authentication provider.
The only way you can come around that is to use javascript to convert the fragment values to query parameters by replacing the '#' with '?' and redirecting to the endpoint in your server controller.
I suppose the easiest way is to handle all that from server, meaning you get get the request in server, send a javascript code to the browser on the fly, that replaces the '#' into '?' and redirects to your second endpoint which reads the token as strong parameter.
Here how you can do it in ASP.NET Core 3.1:
[AllowAnonymous]
[HttpGet("authredirect")]
[Produces("text/html")]
public virtual ContentResult ConvertUrlFragmentToQueryParamThenRedirect()
{
return Content("<html><script>window.location.href=window.location.href.replace('#', '?').replace('authredirect', 'authparams')</script></html>", "text/html");
}
[AllowAnonymous]
[HttpGet("authparams")]
public virtual void GetAccessToken([FromQuery] string access_token)
{
// now you have your access token server side here
}
Please remember to set your redirectUrl to the correct one, in this case 'YOUR REDIRECT URL/authredirect'.

What is the proper api url for this method?

I am consuming an api, the guy working in the backend uses c# and he could not explain to me the methods other than his code. But I don't have experience in c#. Can someone translate to me these lines and tell me what is the url part and what are the body params if any. Thanks!
[WebInvoke(Method = "POST",
        UriTemplate = "UploadCat/{token}/{BID}/{CID}/{CAT}/{DATA}")]
        public HttpResponse UploadCat(string token, string BID, string CID, string CAT, List<CLMobileChangeDTO> DATA)
Depending on the encoding you could hit this API with curl like:
curl -X POST http://hostname/UploadCat/mytoken/myBID/myCID/myCAT/encodedDATA
The tricky part is how the framework you are using will encode a list of objects into URL safe characters to put it on the path. I don't think there is enough information in that code snippet to determine that.
Ideally you would use the post body to send List DATA instead of a path parameter.

How do I set out Attribute in Api Controller

is it possible to use out attribute in a Api Controller method? I'm using C#.
for exp:
[HttpGet]
public string GetWhatever(string type, string source,out int errorCode, out string errorMessage)
if it is, an example of how to call it and get the out value would be great.
No, this is not possible. Only the return value is used and sent to the client.
You should sent a proper HTTP status code and the error message in body. Have a look at this: http://www.asp.net/web-api/overview/error-handling/exception-handling
I believe you miss-understand the usage of the Web API.
Your Web Api method will not be called like any other C# class method, unless you access the library directly and reference the api controller and its method like any other C# class.
The method will be called via the ASP.NET action selector and that will depend on your HTTP verb (GET, PUT, POST, DELETE or PATCH) and depending on the type and the number of your parameters.
Now your method can return your data or returns error depending on your situation, but eventually all your responses will convert to statuscode/content/error,...etc which is what the HTTP protocol understands and deals with.
for example your method can return Ok Status code (200), or Notfound status code 404 depending on where your request found the requested resource or not.
You can start with this article about Web API 2, hopefully you get a better understanding.
Hope that helps.

How to send JSon array to remote asmx webservice using c#?

In my application i've to send request to a remote asmx web service which is asking for a number of parameters. There is a parameter which is asking for json array. But i can't figure it out that how can i input my json string in the asmx url.(There is no issues with other string values for other parameters).
Thanks in advance.
It's my understanding that unless the webservice has been heavily customised, you are going to need to pass that parameter in the request body rather than as a GET parameter. For example (with jQuery):
var data = {
paramName: ['this', 'is', 'the', 'array']
};
$.post('service.asmx/Method?getParam1=herp&getParam2=derp', data)
.done(function(d)
{
console.log('Response: ' + JSON.stringify(d));
});
It's been a while since I used an ASMX service, and I'm not 100% positive that you can mix parameters like that. I have a feeling that if you put anything in the body, you have to put everything in it.

Categories