401 error when using a web service in sapui5 - asp.net

I am implementing a web service into my sapui5 table by
var oModel = new sap.ui.model.odata.ODataModel("http://mywebservice.com/security.svc", false);
sap.ui.getCore().setModel(oModel);
When I launch my code in a web browser and inspect element, I am getting the following errors:
Failed to load resource: the server responded with a status of 401 (Unauthorized)
XMLHttpRequest cannot load http://mywebservice.com/security.svc/$metadata. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:53457' is therefore not allowed access. The response had HTTP status code 401.
I also tested it in Fiddler and I get:
HTTP/1.1 401 Unauthorized
Cache-Control: private
Server: Microsoft-IIS/8.0
Set-Cookie: ASP.NET; path=/; HttpOnly
X-AspNet-Version: 4.0.30319
WWW-Authenticate: Negotiate
WWW-Authenticate: NTLM
X-Powered-By: ASP.NET
Date: Tue, 09 Jun 2015 19:33:51 GMT
Content-Length: 0
Proxy-Support: Session-Based-Authentication
Any help on how to fix the 401 error would be greatly appreciated.

Creating a new ODataModel, it tries to fetch the metadata for the service you have called.
It's basically XMLHttpRequest to a different domain(http://mywebservice.com) than you page(localhost) is on.So the browser is blocking it as it usually allows a request in the same origin for security reasons. Read about same-origin policy
Solution:
You need to do something different when you want to do a cross-domain request.
the origin (where the page with JavaScript is at) and the target: http://mywebservice.com (where the JavaScript is trying to reach) domains must be the exact same.
A tutorial about how to achieve that is Using CORS.
In .NET server,you can configure this in web.config as below
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="your_clientside_websiteurl" />
</customHeaders>
</httpProtocol>
<system.webServer>

Just clone the shortcut for chrome on your desktop, and then in the shortcut properties add the parameter --disable-web-security at the end of chrome executable path
e.g
"C:\Program Files\Google\Chrome\Application\chrome.exe" --disable-web-security
NB:add that parameter --disable-web-security in Target location after one space

Related

Why does my Web API return 404 on all resources when called from a Console app?

I have a little Web API, almost directly from the standard VS project template, i.e. Home and Values controllers, and lots of MVC cruft. It is set to run and debug under IIS 10.
I have set up tracing by adding the package Microsoft.AspNet.WebApi.Tracing and the following code in WebApiConfig:
public static void Register(HttpConfiguration config)
{
config.EnableSystemDiagnosticsTracing();
SystemDiagnosticsTraceWriter traceWriter = config.EnableSystemDiagnosticsTracing();
traceWriter.IsVerbose = true;
traceWriter.MinimumLevel = TraceLevel.Debug;
config.Services.Replace(typeof(ITraceWriter), new SimpleTracer());
...
...
}
SimpleTracer is an ITraceWriter that writes to a text file.
When I call the API from outside the VS ecosystem, i.e. from PostMan in Chrome, a bad url, that results in a 404 error message, and the creation of a new trace file if there's not already one. Of I call it from PostMan with a good url, I get the expected result, and a trace of the request in the trace file.
When I call it from my Console app, even with a good url, I still get a 404 error response, and nothing is written to the trace file. I made sure by removing it and IIS doesn't even re-create it when using the .exe client.
If I call it from the compiled .exe from outside VS, I get the same error.
Then, when I set the Web API to use IIS Express, everything works perfectly. Do I need CORS for calls from non-web apps, does IIS need an extra header in this case? What is wrong?
EDIT A: This is the request when I use PostMan, and it returns a 200 and the expected list of strings.
GET /DemoApi/api/values HTTP/1.1
Host: localhost
Content-Type: application/json
Cache-Control: no-cache
Postman-Token: f9454ffc-6a8d-e1ed-1a28-23ed8166e534
and the response and headers:
["value1","value2","value3","value4","value5","value6","value7"]
Cache-Control →no-cache
Content-Length →64
Content-Type →application/json; charset=utf-8
Date →Tue, 13 Dec 2016 06:20:07 GMT
Expires →-1
Pragma →no-cache
Server →Microsoft-IIS/10.0
X-AspNet-Version →4.0.30319
X-Powered-By →ASP.NET
EDIT B: This is the request sent using HttpClient:
GET http://abbeyofthelema/api/values HTTP/1.1
Accept: application/json
Host: abbeyofthelema
Connection: Keep-Alive
The only real difference is that because Fiddler doesn't capture traffic from localhost, I had to use my computer name instead. The same recipient still gets the request.
The response here is:
HTTP/1.1 404 Not Found
Cache-Control: private
Content-Type: text/html; charset=utf-8
Server: Microsoft-IIS/10.0
X-Powered-By: ASP.NET
Date: Tue, 13 Dec 2016 08:07:25 GMT
Content-Length: 4959
According to Timothy Shields at the following link
Why is HttpClient BaseAddress not working?
You must place a slash at the end of the BaseAddress, and you must not place a slash at the beginning of your relative URI

HTTP Client putAsync (Error 404 Method not Allowed)

I try to update an object with WEB API hosted on a remote server. I recover well the object but at the time of the change, the answer gives 404 method not Allowed. I tested to host my service in a machine of my colleague just nearby. It works well. Is what is needed to make a configuration or something else?
Thank you a lot.
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage responsse = client.PutAsJsonAsync("api/Collaborateurs/" + coll.matricule_collaborateur, coll).Result;
if (responsse.IsSuccessStatusCode) {
}
Error:
{StatusCode: 405, ReasonPhrase: 'Method Not Allowed', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
Date: Thu, 12 Nov 2015 14:28:10 GMT
Server: Microsoft-IIS/7.5
X-Powered-By: ASP.NET
Content-Length: 1343
Allow: GET
Allow: HEAD
Allow: OPTIONS
Allow: TRACE
Content-Type: text/html
}}
WebDAV is know to interfere with the verb PUT. Try uninstalling WebDAV if it is present on the server and you do not use it.
It may also be that you need to contact the remote server's administrator. PUT is sometimes blocked by network switches/routers. I.e. there well may be nothing you can do to fix this with code. Try using POST instead.

POST https://www.linkedin.com/uas/oauth2/accessToken HTTP/1.1 results in Method Not Found on LinkedIn

I am using the LinkedIn Owin Middleare and started running into issues this morning and have now reproduced it to the below error:
POST https://www.linkedin.com/uas/oauth2/accessToken HTTP/1.1
Content-Type: application/x-www-form-urlencoded
Host: www.linkedin.com
Cookie: bscookie="v=1&201504071234373bc02b47-9d08-477f-8375-b80b281ef416AQEptFjv8jXPI93YmF-H-3kvnwSLwBF8"; bcookie="v=2&46f6f299-6702-48bf-8634-7ba023bd5099"; lidc="b=LB23:g=218:u=215:i=1428412320:t=1428487523:s=AQEQQq6vlEKPT3LW8c0cPEzRTKp-ToxL"
Content-Length: 267
Expect: 100-continue
Connection: Keep-Alive
grant_type=authorization_code&code=AQQRSgEH8vczSFJKNxtMpunzjYN6YJxoF2hiX_d9RVkqBvMC7TzRpur0p9NJFdQOUNf8RmFyj_cCg3ENTucRw5e-gQfEZ5sPGoujiFRsQ8Tb0pLnaog&redirect_uri=http%3A%2F%2Flocalhost%3A1729%2Fsignin-linkedin&client_id=&client_secret=
Results in method not found.
HTTP/1.1 405 Method Not Allowed
Date: Tue, 07 Apr 2015 13:13:16 GMT
Content-Type: text/html
Content-Language: en
Content-Length: 5487
X-Li-Fabric: PROD-ELA4
Strict-Transport-Security: max-age=0
Set-Cookie: lidc="b=LB23:g=218:u=215:i=1428412396:t=1428487523:s=AQExeP2uX-7KXQv79NIZmW0LB09uE4eJ"; Expires=Wed, 08 Apr 2015 10:05:23 GMT; domain=.linkedin.com; Path=/
Pragma: no-cache
Expires: Thu, 01 Jan 1970 00:00:00 GMT
Cache-Control: no-cache, no-store
Connection: keep-alive
X-Li-Pop: PROD-IDB2
X-LI-UUID: 0FM/jIG90hPAzyhAqCsAAA==
Looking for anyone to confirm that there was a change on linkedin causing this error and that its not application specific.
Note that i removed teh above clientid/secrets.
I also spent most of the morning off and on trying to get this to work. Frustratingly it worked fine using Advanced Rest Client chrome tool. A combination of this and fiddler showed the only difference in the header was that Expect: 100-continue flag in the header. The only way I was able to get it to be set to false was in the web.config section
<system.net>
<settings>
<servicePointManager expect100Continue="false" />
</settings>
</system.net>
Hope this helps.
I ran into this issue this morning too (I'm using DotNetOpenAuth). It looks like this is related to the use of the following request header: Expect: 100-continue
After removing this request header, the HTTP/1.1 405 Method Not Allowed response no longer occurs. Obviously this isn't much help if you don't have access to the source code!
I'm assuming this is due to a change in LinkedIn as I only started experiencing problems this morning. I'm guessing they'll need to look into a fix for this.
I started having this issue today. After some research about Expect: 100-continue I found that putting
System.Net.ServicePointManager.Expect100Continue = false;
in my Application_Start() function inside of Global.asax, takes out the 100-continue from the request and my login with LinkedIn is now working again.
Not a permanent fix as I would like to now why it broke in the first place.
I had same issue also use DotNetOpenAuth.
How I fix:
I remove from request header "Expect: 100-continue"
in my case redirect_uri was encoded and I remove encode for redirect_uri (for request to https://www.linkedin.com/uas/oauth2/accessToken )
For those using Owin Middleware and Owin.Security.Providers
A pre-release nuget was created with a fix.
https://www.nuget.org/packages/Owin.Security.Providers/1.17.0-pre
This works for now. But until we know what linkedin has changed or comes with statement about what they changed people can use this as a hotfix.
Alittle more background on the fix can be found at :
https://github.com/RockstarLabs/OwinOAuthProviders/issues/87#issuecomment-90838017
But the root cause is that LinkedIn changed something on there accessToken endpoint causing most of the libs using linkedin SSO had to apply a hotfix, but we yet haven't heard anything from linkedin.
Found a solution for curl, pretty simple:
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Expect:') );

asp.net web service return invalid XML

i have a web service its run locally, but when i hosted on AWS its not running from my client I get the error "System.ServiceModel.ProtocolException: There is a problem with the XML ..."
I tried to call it from SoapUI its working
this is the request :
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:her="http://HerakiNet.com/">
<soapenv:Header/>
<soapenv:Body>
<her:SayHello>
<!--Optional:-->
<her:name>Ahmed</her:name>
</her:SayHello>
</soapenv:Body>
</soapenv:Envelope>
and the response as raw:
HTTP/1.0 200 OK
Cache-Control: private, max-age=0
Content-Type: text/xml; charset=utf-8
Date: Sun, 29 Dec 2013 11:12:39 GMT
Server: Microsoft-IIS/8.0
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Content-Length: 359
X-Cache: MISS from UB15-WMJ-080811
Via: 1.1 UB15-WMJ-080811:3128 (Lusca)
Connection: keep-alive
<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><soap:Body><SayHelloResponse xmlns="http://HerakiNet.com/"><SayHelloResult>Hello , Ahmed</SayHelloResult></SayHelloResponse></soap:Body></soap:Envelope>
can any one help??
this is the result of executing a small test from DotNet App:
System.ServiceModel.ProtocolException: There is a problem with the XML that was
received from the network. See inner exception for more details. ---> System.Xml
.XmlException: The data at the root level is invalid. Line 1, position 1 ...
the application code is:
var client = new EstimatorWcfService.EstimatorWebServiceSoapClient();
Console.WriteLine(client.SayHello("Ahmed"));
According to error, you are calling wrong end point url from your client.
There would be two urls in service tag in your wsdl one for http and another for https. May be you are using https one instead of http. Cross check from soap ui (at top of your request).

How to Response.Write on IIS7.5?

i am trying to write out a response to the client:
response.StatusCode = (int)HttpStatusCode.BadRequest;
response.ClearContent();
response.Write(String.Format(
"<!doctype html>"+CRLF+
"<html>" + CRLF +
"<head><title>{0}</title></head>" + CRLF +
"<body><h1>{0}</h1>"+CRLF+
"{1}"+CRLF+
"</body>" + CRLF +
"</html>",
response.Status, "The grob must be in the frobber."));
response.Flush();
response.End();
The code works fine when running on the localhost (Visual Studio (2010 (Windows 7 (Professional (64-bit))))) development Cassini web-server:
HTTP/1.1 400 Bad Request
Server: ASP.NET Development Server/10.0.0.0
Date: Tue, 17 Jul 2012 15:56:42 GMT
X-AspNet-Version: 4.0.30319
Cache-Control: private
Content-Type: text/html
Connection: Close
<!doctype html>
<html>
<head><title>400 Bad Request</title></head>
<body><h1>400 Bad Request</h1>
The grob must be in the frobber.
</body>
</html>
But when i deploy the web-site to Windows Server 2008 R2 running IIS7.5, the same code doesn't work:
HTTP/1.1 400 Bad Request
Cache-Control: private
Content-Type: text/html
Server: Microsoft-IIS/7.5
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Tue, 17 Jul 2012 15:57:44 GMT
Content-Length: 11
Bad Request
How do i perform Response.Write from IIS?
By default, IIS 7 will change the response if the code is >= 400
http://msdn.microsoft.com/en-us/library/ms690497(v=vs.90).aspx
But you can change this in the httpErrors element of system.webServer.
<httpErrors existingResponse="PassThrough" />
EDIT: this will break CustomErrors, if you are using that. You might be better off returning a 400 without a response, then setting up web.config to redirect to a custom page for 400 errors.
<customErrors mode="On">
<error statusCode="400" redirect="Frobber.htm" />
</customErrors>
I ran into this exact issue & spent a few frustrating hours today noodling through it. In my case, I am sending potentially very large CSV data directly down to the client via Response.Write and flushing it every 3k records or so. It works great from my local environment, but failed when deployed to IIS 7.5 on a Windows 2008 server. No exceptions, just an empty CSV at the client.
Turns out Dynamic Compression was enabled for my application. It can be disabled via web.config directly, or in your IIS MMC interface. You can validate this by using your browser's tools to examine the headers of the response you're receiving.
Content-Encoding:gzip
Disable dynamic compression (not sure how/why it was enabled originally), and it worked fine. It might not be your issue, but it was mine. I fished around for most of the day on this one and didn't see it answered directly, so I figured I'd throw it out there. Also, the size of the result set didn't matter; a 5kb file & 3Gb file had the same problem.
Have you checked that asp.net is enabled on the server? You need to use the Windows server manager to check the features have been installed.
I've just tried your code on my server & despite what I assume is a typo around casing of response, it worked as expected.

Resources