odata datajs CRUD operation fails in IE (OData) - jsonp

I have this code below, which adds a new "Activity" in my "activity" table/entity thru WCF Data Services. Now all is fine and dandy when I run this in Chrome and Firefox, but in IE10 it responds with the following error...
{"error":{"code":"","message":{"lang":"en-US","value":"An error occurred while processing this request."}}}
Here is what my code looks like...
function addActivity( newActivity )
{
var newActivity = { ActivityName: newActivity };
var requestOptions = {
//headers: { "DataServiceVersion": "1.0" },
method: "POST",
requestUri: uriActivity,
data: newActivity
};
OData.request( requestOptions, AddSuccessCallback, AddErrorCallback );
}
I'm also using the following packages, for all it's worth...Thanks a lot for reading up to here. Many special thanks in advance for your input.
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="datajs" version="1.0.3" />
<package id="jQuery" version="1.7.2" />
<package id="Microsoft.Data.Edm" version="5.0.1" />
<package id="Microsoft.Data.OData" version="5.0.1" />
<package id="Microsoft.Data.Services" version="5.0.1" />
<package id="Microsoft.Data.Services.Client" version="5.0.1" />
<package id="System.Spatial" version="5.0.1" />
</packages>
Trace looks like this...
HTTP/1.1 400 Bad Request
Server: ASP.NET Development Server/11.0.0.0
Date: Mon, 09 Jul 2012 07:55:17 GMT
X-AspNet-Version: 4.0.30319
X-Content-Type-Options: nosniff
DataServiceVersion: 1.0;
Content-Length: 1159
Cache-Control: private
Content-Type: application/json;odata=verbose;charset=utf-8
Connection: Close
{"error":{"code":"","message":{"lang":"en-US","value":"An error occurred while processing this request."},"innererror":{"message":"A node of type 'EndOfInput' was read from the JSON reader when trying to read the start of an entry. A 'StartObject' node was expected.","type":"Microsoft.Data.OData.ODataException","stacktrace":" at Microsoft.Data.OData.Json.ODataJsonEntryAndFeedDeserializer.ReadEntryStart()\r\n at Microsoft.Data.OData.Json.ODataJsonReader.ReadEntryStart()\r\n at Microsoft.Data.OData.Json.ODataJsonReader.ReadAtStartImplementation()\r\n at Microsoft.Data.OData.ODataReaderCore.ReadImplementation()\r\n at Microsoft.Data.OData.ODataReaderCore.ReadSynchronously()\r\n at Microsoft.Data.OData.ODataReaderCore.InterceptException[T](Func`1 action)\r\n at Microsoft.Data.OData.ODataReaderCore.Read()\r\n at System.Data.Services.Serializers.EntityDeserializer.ReadEntry(ODataReader odataReader, SegmentInfo topLevelSegmentInfo)\r\n at System.Data.Services.Serializers.EntityDeserializer.Read(SegmentInfo segmentInfo)\r\n at System.Data.Services.Serializers.ODataMessageReaderDeserializer.Deserialize(SegmentInfo segmentInfo)"}}}

Looks like I need to serve my pages thru HTTP. Loading them from Windows doesn't work especially where IE is concerned.

Related

NLog 5.0 - Filtering Microsoft.Extensions.Logging logs doesn't work

I've migrated an ASP.NET Core project from 3.1 to 6.0 and now I can't get rid of many Microsoft logs when using an Authentication middleware
For example, I always have those logs when I call my API endpoint having[Authorize(Roles = "admin")] annotation from an unauthorized client
2022-06-08 14:36:28.1023 INFO Microsoft.Extensions.Logging.LoggingExtensions.AuthenticationSchemeChallenged AuthenticationScheme: Bearer was challenged.
2022-06-08 14:40:58.7025 INFO Microsoft.Extensions.Logging.LoggingExtensions.AuthenticationSchemeChallenged AuthenticationScheme: Bearer was challenged.
2022-06-08 14:42:53.8049 INFO Microsoft.Extensions.Logging.LoggingExtensions.AuthenticationSchemeChallenged AuthenticationScheme: Bearer was challenged.
I also have those logs when calling another API using a Refit Client
2022-06-07 13:38:35.6434 INFO Microsoft.Extensions.Http.Logging.LoggingHttpMessageHandler+Log.RequestEnd Received HTTP response headers after 78.0306ms - 200
2022-06-07 13:38:35.6434 INFO Microsoft.Extensions.Http.Logging.LoggingScopeHttpMessageHandler+Log.RequestPipelineEnd End processing HTTP request after 81.3323ms - 200
2022-06-07 13:38:35.6947 INFO Microsoft.Extensions.Http.Logging.LoggingScopeHttpMessageHandler+Log.RequestPipelineStart Start processing HTTP request POST https://api.removed.com/endpoint
2022-06-07 13:38:35.6947 INFO Microsoft.Extensions.Http.Logging.LoggingHttpMessageHandler+Log.RequestStart Sending HTTP request POST https://api.removed.com/endpoint
2022-06-07 13:38:35.8336 INFO Microsoft.Extensions.Http.Logging.LoggingHttpMessageHandler+Log.RequestEnd Received HTTP response headers after 136.3691ms - 200
2022-06-07 13:38:35.8336 INFO Microsoft.Extensions.Http.Logging.LoggingScopeHttpMessageHandler+Log.RequestPipelineEnd End processing HTTP request after 139.7244ms - 200
2022-06-07 13:38:35.8418 INFO Microsoft.Extensions.Http.Logging.LoggingHttpMessageHandler+Log.RequestStart Sending HTTP request POST https://api.removed.com/endpoint
2022-06-07 13:38:37.2229 INFO Microsoft.Extensions.Http.Logging.LoggingHttpMessageHandler+Log.RequestEnd Received HTTP response headers after 1379.9163ms - 200
2022-06-07 13:38:37.2229 INFO Microsoft.Extensions.Http.Logging.LoggingScopeHttpMessageHandler+Log.RequestPipelineEnd End processing HTTP request after 2437.5144ms - 200
Program.cs
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using NLog;
using NLog.Web;
using System;
namespace CDL_CloudServerApi
{
public class Program
{
public static void Main(string[] args)
{
var logger = LogManager.Setup().LoadConfigurationFromAppSettings().GetCurrentClassLogger();
try
{
logger.Debug("Create Host");
CreateHostBuilder(args).Build().Run();
}
catch (Exception ex)
{
//NLog: catch setup errors
logger.Error(ex, "Stopped program because of exception");
throw;
}
finally
{
LogManager.Shutdown();
}
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureLogging(logging =>
{
logging.ClearProviders();
logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Warning);
})
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder
.UseUrls("http://*:8282")
.UseStartup<Startup>()
.UseNLog();
});
}
}
nlog.config
<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
autoReload="true"
throwExceptions="false"
internalLogLevel="Off"
internalLogFile="c:\temp\nlog-internal.log">
<!-- enable asp.net core layout renderers -->
<extensions>
<add assembly="NLog.Web.AspNetCore"/>
</extensions>
<variable name="verbose" value="${longdate} ${uppercase:${level}} ${callsite:className=true:fileName=false:includeSourcePath=false:methodName=true:cleanNamesOfAnonymousDelegates=false:skipFrames=0} ${message}" />
<variable name="verbose_inline" value="${replace:inner=${verbose}:searchFor=\\r\\n|\\n:replaceWith=->:regex=true} ${exception:format=toString,Data:maxInnerExceptionLevel=10}"/>
<!-- 5GB max size per log-->
<targets>
<target name="logfile" xsi:type="File"
fileName="${basedir}/log/logfile.txt"
layout="${verbose_inline}"
archiveFileName="${basedir}/log/archives/log.{#}.txt"
archiveNumbering="Date"
archiveDateFormat="yyyy-MM-dd"
archiveEvery="Day"
archiveAboveSize="5000000000"
maxArchiveFiles="14"
maxArchiveDays="7"
concurrentWrites="true"
keepFileOpen="false" />
</targets>
<rules>
<!--Skip non-critical Microsoft logs and so log only own logs-->
<logger name="Microsoft.*" finalMinLevel="Warn" />
<logger name="System.Net.Http.*" finalMinLevel="Warn" />
<logger name="*" minlevel="Info" writeTo="logfile" />
</rules>
</nlog>
You should include ${logger} in your layout, so you can see the logger-name that should be filtered away.
<variable name="verbose" value="${longdate} ${level:uppercase=true} ${logger} ${message}" />
<variable name="verbose_inline" value="${replace-newlines:replacement=->:${verbose}} ${exception:format=toString,Data}"/>
Alternative update to minLevel="Warn" for everything:
<logger name="*" minlevel="Warn" writeTo="logfile" />
Alternative specify RemoveLoggerFactoryFilter = false for NLogProviderOptions when calling UseNLog() as mentioned in NLog 5.0 - List of major changes. Then NLog will continue to follow Microsoft Logggng Filter-configuration.
Notice that you should be careful with ${callsite}, since it introduces a huge performance overhead.
Notice that ${replace-newlines} is faster than ${replace} with regex.

“405 method not allowed” for “DELETE” method

I'm getting a '405 Method Not Allowed' when I attempt for a DELETE in my staging environment.
Is there something I should be looking out for?
When I run it on my local machine (IIS 10.0) it works fine and is able to delete an ID but when I run it on my staging environment it doesn't work and returns a 405 error on swagger.
This only seems to be occurring for all delete endpoints
This is how I've implemented delete endpoints:
[HttpDelete]
[Route("{Id}")]
current output from response header:
allow: GET, HEAD, OPTIONS, TRACE
content-length: 1293
content-type: text/html
date: Mon, 14 Sep 2020 04:15:15 GMT
server: Microsoft-IIS/8.5
x-powered-by: ASP.NET
x-powered-by-plesk: PleskWin
I've got the current setup for my startup.cs
private static void ConfigureCors(IServiceCollection services)
{
services.AddCors(o => o.AddPolicy("testAppPolicy", builder =>
{
builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.Build();
}));
}
I know it's quite a vague question but any tips on where I could start looking on how to debug this situation?
According to your description and error message, I suggest you could firstly make sure you have installed the right asp.net core module for the staging server.
Then I suggest you could try to remove the WebDAVModule in the IIS server.
More details, you could try to modify the web.config as below format.
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.webServer>
<modules>
<remove name="WebDAVModule" />
</modules>
<handlers>
<remove name="WebDAV" />
<!-- I removed the following handlers too, but these
can probably be ignored for most installations -->
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<remove name="OPTIONSVerbHandler" />
<remove name="TRACEVerbHandler" />
</handlers>
<aspNetCore processPath="yourasp.net core config"
stdoutLogEnabled="false"
stdoutLogFile=".\logs\stdout" />
</system.webServer>
</configuration>

IIS 10 automatically adds wrong CORS header

I have installed IIS CORS moudule on the server.
On the OPTIONS request I get :
Access-Control-Allow-Credentials: true
Access-Control-Allow-Headers: content-type
Access-Control-Allow-Methods: GET, HEAD, POST, PUT, DELETE
Access-Control-Allow-Origin: ### the actual good origin ###
Date: Fri, 13 Sep 2019 06:32:11 GMT
Server: Microsoft-IIS/10.0
Vary: Origin
X-Powered-By: ASP.NET
But on the POST request I get
Access-Control-Allow-Origin: http://localhost/
Content-Length: 1216
Content-Type: application/json; charset=utf-8
Date: Fri, 13 Sep 2019 06:32:11 GMT
Server: Microsoft-IIS/10.0
X-Powered-By: ASP.NET
In web config i have
<cors enabled="true">
<add origin="### the actual good origin ###" allowCredentials="true" >
<allowHeaders allowAllRequestedHeaders="true" />
<allowMethods >
<add method="GET" />
<add method="HEAD" />
<add method="POST" />
<add method="PUT" />
<add method="DELETE" />
</allowMethods>
</add>
</cors>
The WebService I try to call is an WCF webservice.
How can I disable the "localhost" header on the POST request?
I am not setting anything static header, neither in web.config nor in IIS itself
I suggest you try to add the Global.asax file to the WCF project, which is used to solve the CORS issue.
protected void Application_BeginRequest(object sender, EventArgs e)
{
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
{
HttpContext.Current.Response.AddHeader("Cache-Control", "no-cache");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Cache-Control, Pragma, Origin, Authorization, Content-Type, X-Requested-With,Accept");
HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
HttpContext.Current.Response.End();
}
Alternatively, we could also configure it in webconfig file.
protected void Application_BeginRequest(object sender, EventArgs e)
{
if (Request.Headers.AllKeys.Contains("Origin") && Request.HttpMethod == "OPTIONS")
{
Response.End();
}
}
Webconfig.
<system.webServer>
<modules runAllManagedModulesForAllRequests="true" />
<directoryBrowse enabled="true" />
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*"/>
<add name="Access-Control-Allow-Headers" value="content-type" />
<add name="Access-Control-Allow-Methods" value="GET,POST,PUT,DELETE,OPTIONS" />
</customHeaders>
</httpProtocol>
</system.webServer>
Feel free to let me know if the problem still exists.

Enable CORS in Azure web

What I´m trying to do is to enable CORS (Cross-origin Resource Sharing) for .net MVC 5 Azure website when calling a https service (not my own) from my JavaScript.
I always get the same error
XMLHttpRequest cannot load https://someservice-I-have-no-control-over. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://my.azurewebsites.net' is therefore not allowed access. The response had HTTP status code 400.
I have managed to enable this when developing locally, setting my project to https and adding the following to web.config
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Methods" value="GET, POST, OPTIONS"/>
<add name="Access-Control-Allow-Headers" value="Content-Type, Accept, SOAPAction"/>
<add name="Access-Control-Max-Age" value="1728000"/>
</customHeaders>
</httpProtocol>
</system.webServer>
That adds the 'Access-Control-Allow-Origin' header. But that does not seem to work on the Azure website.
And I can´t find any settings like in the Mobile Services where you can allow this like you see here.
Since I know you are all going to ask for code (that works locally btw) there you have the simple Jquery call to the service
$.ajax({
url: 'https://someservice-I-have-no-control-over',
dataType: 'json',
contentType: 'application/json',
type: 'GET',
success: function (response) {
$.each(response, function (key, value) {
console.log("success"); //Doesn´t happen! :-(
});
},
error: function (xhr, text, error) {
if ($.isFunction(onError)) {
onError(xhr.responseJSON);
}
}
});
So any thoughts?
Edit 1
Just to clarify a little.
I am calling a service that I have no control over that is a https one, in a javascript (not a controller) that is mine.
Edit 2
Ok I thought that I could intercept the response from the third party service and add this header before the browser rejects it. As I see it that is not possible (right?). But how come it works locally?
If I capture the call to this service with e.g LiveHTTPHeaders I get the following response where there is not a "Access-Control-Allow-Origin" restriction (so way does it work locally?).
Request (to https://someservice-I-have-no-control-over.com)
GET /someservice-I-have-no-control-over/SomeAction/44 HTTP/1.1
Host: someservice-I-have-no-control-over.com
User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64; rv:37.0) Gecko/20100101 Firefox/37.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Connection: keep-alive
If-None-Match: "53867cff-96b0-411f-88b7-d84765f9f8e8"
Cache-Control: max-age=0
Reply
HTTP/1.1 304 Not Modified
Cache-Control: max-age=900
Server: Microsoft-IIS/8.5
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS
Date: Tue, 24 Feb 2015 11:06:53 GMT
Not possible.
It works locally because it's the server that must have the allow headers, and when you call your own webserver from your javascript you can add those headers.
When you call the real website they do probably not add the CORS allow header (Access-Control-Allow-Origin) and your request is therefore denied.
What you could do is either to use JSONP or proxy all requests through your own website.
You could for instance use my CORS proxy: https://github.com/jgauffin/corsproxy. It's intended usage is for IE9 and below, but works just as fine for all requests.
WebApiConfig I set it the WebApiConfig class and it worked. I also had issues on Azurewebsites when trying to set it via web.config.
Try this in WebApiConfig:
var cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(cors);
You can edit the "", "", "*" if you don't want to allow everything.
If you're using Owin, you can do this in the Startup.cs file:
app.UseCors(CorsOptions.AllowAll);
Use this if and only if you intentionally plan to expose your API to all origins and headers.
Else, you can try it this way by decorating your controller or specific methods:
[EnableCors(origins: "http://someCallingService", headers: "*", methods: "*")]
Check out THIS article
I addressed this by installing the following package:
Microsoft.AspNet.WebApi.Cors
...then using the Config.EnableCors() as described above and altering my web.config transform:
In WebApiConfig.cs:
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
config.EnableCors();
// Continue configuration as you wish...
}
Then, in the web.config transform, in my case named web.PPE.config because it's for Pre-Production:
<system.webServer>
<httpProtocol>
<!-- custom headers necessary for CORS -->
<customHeaders xdt:Transform="Replace">
<clear /> <!-- the clear here is important! -->
<add name="Access-Control-Allow-Origin" value="http://url-that-is-allowed-to-communicate-with-this-server.com" />
<!-- must match server DNS address or SignalR can't communicate with Hub remotely -->
<add name="Access-Control-Allow-Headers" value="Content-Type" />
<add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
<add name="Access-Control-Allow-Credentials" value="true" />
</customHeaders>
</httpProtocol>
</system.webServer>
YMMV on whether to include the Allow-Credentials option. I found that necessary with my need, which was to enable access to a SignalR hub on a remote Azure webserver/app instance.
Good luck!

Consuming SOAP web service in SENCHA TOUCH?

I have found this post that worked for me but I recieved a HTML response instead of a XML one which is what I need for my app.
How to consume SOAP web service in SENCHA TOUCH?
This is my request to my server... I know I should be doing a POST action as this guy was told, but I still get a root node error.
Is this the proper way to consume a WebService, or there is another way to consume in Sencha using data models and stores? I have already saw an example using CFC but I am using IIS 7.5
POST /url/mobilews.asmx HTTP/1.1
Host: 10.0.1.182
Content-Type: text/xml; charset=utf-8
Content-Length: length
SOAPAction: "http://tempuri.org/HelloWorld"
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<HelloWorld xmlns="http://tempuri.org/" />
</soap:Body>
</soap:Envelope>
Ext.Ajax.request({
method: 'GET',
url: 'http://url/mobileservice/mobilews.asmx?op=HelloWorld',
params: { method: 'HelloWorld', format: 'json' },
success: function (response, request) {
alert('Working!');
alert(response.responseText);
},
failure: function (response, request) {
alert('Not working!');
}
});
Here goes the error message:
<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><soap:Body><soap:Fault><soap:Code><soap:Value>soap:Receiver</soap:Value></soap:Code><soap:Reason><soap:Text xml:lang="en">System.Web.Services.Protocols.SoapException: Server was unable to process request. ---> System.Xml.XmlException: Data at the root level is invalid. Line 1, position 1.