how to pass a decimal number to a rest web service - c#

I am wanting to pass a decimal number (1.23) to my WCF-REST web service.
I keep getting a 'resource cannot be found' error. I expect that I'm encountering some security feature of IIS where urls that contain a dot are a resource. Does anyone have a suggestion on how to pass a decimal number to my webservice?
Sample url... http://localhost/restdataservice.svc/echo/2.2
Operation Contract
[OperationContract]
[WebGet(UriTemplate = "echo/{number}")]
string Echo(string number);
And implementation
public string Foo(string number)
{
return number;
}

You should look at IIS log to see the problem. One thing that can cause such problem is UrlScan. It has UrlScan.ini config file, where you can find AllowDotInPath parameter. If it is set to 0, requests such as above would be rejected. Just change it to 1 (but don't forget to ensure, that you don't allow directory traversals by rejecting urls with ..).

You may want to consider sending that number to your resource in a request representation using a POST request.

This should work fine out of the box, I cannot reproduce this problem with a similar basic setup - are you sure the default route for your echo method is set correctly?

I had a similar problem calling a method on a WCF OData Server.
The problem was that a decimal parameter requires an 'm' at the end.
http://localhost/restdataservice.svc/echo/2.2m

Related

Prevent URL encoding at QueryString.Add()

I am making a Restful api using OData, and for some reasons I want to force the expand filtering inside the middleware.
So if the clients sends in
http://localhost:52973/odata/customers
The Middleware should automatically change it into
http://localhost:52973/odata/customers?$expand=Contact,Address
In order to do this I've made a simple if statement inside my middleware
if (ctx.Request.Path.Value.Contains("customers") && !ctx.Request.QueryString.Value.Contains("?$expand"))
{
string uri = #"?$expand=";
ctx.Request.QueryString = ctx.Request.QueryString.Add(uri, "Contact,Address");
}
Unfortunately, it keeps generating the following: {?%3F%5C$expand%5C%3D=Contact,Address}
I've tried adding backslashes inside the uri string, but that didn't solve it.
I would assume that it is url-encoding ("escaping") the '$' character to make it safer, so I would not approach this problem from that angle. I would modify your consumers of this request to url-decode the request, which may be automatically done. See QueryString.ToUriComponent, and also the QueryString.ToString() method too.

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.

Encrypting URL for WCF Service

When using WCF Data Services, more specifically in DevExtreme's WCF Odata service in c#, is there any way of encrypting the URL queries? I do not want the client to be able to see/modify the URL in order to get access to the data. I want to know if this level of obscurity is available, even if have authentication for the client and that the client only has rights to one ID.
For example:
/AcountsByIntroducerID?entityID=1234
This URL exposes the ID and also allows a client to change the ID number. Would there be any way in WCF that would allow use to turn the above URL into a encrypted string?
Such as: /JDudfj8ddJFDJSLAFDLJuaeouru0
So this can be decrypted on the server side. Thanks!
I had a similar problem to solve. For solve it i used the following pattern
I have encoded url parameters in one base 64 string.
Declare your WCF with one parameter
[ServiceContract]
public interface VCIWCFService
{
[OperationContract]
[WebGet(UriTemplate = "/{encodedParameters}")]
string GetSomething();
}
In backend code you can decode encodedParameters with the following code
string Url = HttpUtility.UrlDecode(encodedParameters);
Url = Convert.FromBase64String(Url );
and you can get a particular parameter with HttpUtility class :
Uri myUri = new Uri(string.format("http://www.nothing.com?{0}",Url));
string param1 = HttpUtility.ParseQueryString(myUri.Query).Get("param1");
I work with Objective-C Ipad app, and i encode the parameters with the inverse system

REST webservice "Bad request"

I'm writing a REST webservice having a method like this:
[WebGet(
UriTemplate = "/Test/{p1}/{p2}",
BodyStyle = WebMessageBodyStyle.Bare,
ResponseFormat = WebMessageFormat.Xml)]
public string Test(string p1, string p2)
{
// Do something here
}
So if I call basurl/Test/prova/test my method Test is invoked with p1="prova" and p2="test" and everything works fine.
Problem comes when I try to use a param having (for example) % char: even translating it in URL code, when I try to call basurl/Test/prova/te%25st I get a
Errore HTTP 400 - Bad Request.
If I use
[WebGet(
UriTemplate = "/Test/{p1}?p2={p2}",
BodyStyle = WebMessageBodyStyle.Bare,
ResponseFormat = WebMessageFormat.Xml)]
public string Test(string p1, string p2)
{
// Do something here
}
and call basurl/Test/prova?p2=te%25st it works.
Why? What can I do to let first syntax work?
UPDATE:
Look at my answer with a possible solution.
If someone finds a better one, please post it!!
Thanks
Googling around I've just found this link:
http://weblogs.asp.net/imranbaloch/archive/2010/04/23/understanding-400-bad-request-exception.aspx
where they say:
ASP.NET Restrictions:
After passing the restrictions enforced by the kernel mode http.sys then the request is handed off to IIS and then to ASP.NET
engine and then again request has to pass some restriction from
ASP.NET in order to complete it successfully.
ASP.NET only allows URL path lengths to 260 characters(only paths, for example http://a/b/c/d, here path is from a to d). This
means that if you have long paths containing 261 characters then you
will get the Bad Request exception. This is due to NTFS file-path
limit.
Another restriction is that which characters can be used in URL path portion.You can use any characters except some characters
because they are called invalid characters in path. Here are some of
these invalid character in the path portion of a URL, <,>,*,%,&,:,\,?.
For confirming this just right click on your Solution Explorer and Add
New Folder and name this File to any of the above character, you will
get the message. Files or folders cannot be empty strings nor they
contain only '.' or have any of the following characters.....
For checking the above situation i have created a Web Application and put Default.aspx inside A%A folder (created from
windows explorer), then navigate to,
http://localhost:1234/A%25A/Default.aspx, what i get response from
server is the Bad Request exception. The reason is that %25 is the %
character which is invalid URL path character in ASP.NET. However you
can use these characters in query string.
The reason for these restrictions are due to security, for example with the help of % you can double encode the URL path portion
and : is used to get some specific resource from server.
So I'm starting to think that my problem is impossible to solve.
I'm sure that this problem is not present in some REST webservice written in PHP and hosted with Apache, so I think it's just a IIS/ASP "security" restriction I can't find a workaround for...
UPDATE WITH FINAL SOLUTION:
I found a solution here: read the article to understand everything.
You should know that it could be risky, so think well before using it.
<system.web>
<httpRuntime requestPathInvalidCharacters="" />
<pages validateRequest="false" />
</system.web>

Categories