Issues calling saveChanges with Breezjs - asp.net-web-api

I'm trying to get breeze to work with my webapi/odata service against an Entity framework model with a sql backend.
I've got it to retrieve data from my database, bit am having trouble when I do a createEntity() and then call saveChanges().
I've configured my batch route like this
var cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(cors);
// Web API routes
config.Routes.MapHttpBatchRoute(
routeName: "WebApiBatch",
routeTemplate: "odata/$batch",
batchHandler: new System.Web.Http.Batch.DefaultHttpBatchHandler(GlobalConfiguration.DefaultServer));
When I call save changes I get an http 500 server error, with the message:
Invalid 'HttpContent' instance provided. It does not have a content type header with a value of 'application/http; msgtype=request'.
Parameter name: content
the stream sent to the server is :
POST http://gx9020-01:91/odata/$batch HTTP/1.1
Accept: multipart/mixed
DataServiceVersion: 2.0
Content-Type: multipart/mixed;boundary=batch_9245-db9a-4873
MaxDataServiceVersion: 3.0
Referer: http://localhost:61678/WebForm1.aspx
Accept-Language: en-US
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko
Connection: Keep-Alive
Content-Length: 731
DNT: 1
Host: gx9020-01:91
Pragma: no-cache
--batch_9245-db9a-4873
Content-Type: multipart/mixed; boundary=changeset_0952-3d90-c3e2
--changeset_0952-3d90-c3e2
Content-Type: application/http
Content-Transfer-Encoding: binary
POST odata/MAP_Counterparty HTTP/1.1
Content-ID: 1
DataServiceVersion: 2.0
Accept: application/atomsvc+xml;q=0.8, application/json;odata=fullmetadata;q=0.7, application/json;q=0.5, */*;q=0.1
Content-Type: application/json
MaxDataServiceVersion: 3.0
{"MAP_CounterpartyID":-1,"SOURCE_SYSTEM":null,"TARGET_SYSTEM":null,"SOURCE_CODE":null,"TARGET_CODE":null,"TARGET_CODE2":null,"DRT_ID":null,"CREATE_DATETIME":null,"MODIFY_DATETIME":null,"Create_User":null,"Modify_User":null}
--changeset_0952-3d90-c3e2--
--batch_9245-db9a-4873--
How can I get the saveChanges() working?

I found the problem. I was using DefaultHttpBatchHandler instead of DefaultODataBatchHandler.

Related

Browser auth popup not showing up in case of ajax cors with basic authentication request

From a web page of domain A, I am firing up an ajax request to domain B in order to get JSON for which basic auth is configured on domain B. I have access to the code on both the domains. I configured the all the required CORS header on domain B (Even made Access-Control-Allow-Origin header value specific and not "*", after reading some stackoverflow) What I am expecting is browser basic auth pop up, But POST request just fails with 401.I can see that server has responded with expected response header for PRE-FLIGHT OPTION request, below the request & response headers of the OPTION & actual POST method call that happens
***OPTION REQUEST***
Host: DOMAIN_B:8085
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:64.0) Gecko/20100101 Firefox/64.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
Access-Control-Request-Method: POST
Access-Control-Request-Headers: x-requested-with
Referer: http://DOMAIN_A:2280/app/
Origin: http://DOMAIN_A:2280
Connection: keep-alive
***OPTION RESPONSE***
HTTP/1.1 200 OK
X-Powered-By: Express
Access-Control-Allow-Origin: http://DOMAIN_A:2280
Vary: Origin
Access-Control-Allow-Credentials: true
Access-Control-Allow-Methods: GET,HEAD,PUT,PATCH,POST,DELETE
Access-Control-Allow-Headers: Content-Type,Authorization,x-requested-with
Access-Control-Max-Age: 1
Allow: GET,POST
Content-Type: text/html; charset=utf-8
Content-Length: 8
Date: Fri, 04 Jan 2019 12:48:48 GMT
Connection: keep-alive
*** ACTUAL POST REQUEST***
Host: DOMAIN_B:8085
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:64.0) Gecko/20100101 Firefox/64.0
Accept: */*
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Referer: http://DOMAIN_A:2280/app/
X-Requested-With: XMLHttpRequest
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Content-Length: 105
Origin: http://DOMAIN_A:2280
Connection: keep-alive
*** ACTUAL POST REQUEST***
HTTP/1.1 401 Unauthorized
X-Powered-By: Express
Vary: X-HTTP-Method-Override, Origin
Access-Control-Allow-Origin: http://DOMAIN_A:2280
Access-Control-Allow-Credentials: true
Access-Control-Allow-Methods: POST,GET,PUT,DELETE
Access-Control-Allow-Headers: Content-Type,Authorization,x-requested-with
Access-Control-Max-Age: 1
WWW-Authenticate: Basic realm=artist
Content-Type: text/plain; charset=utf-8
Content-Length: 12
Date: Fri, 04 Jan 2019 12:48:48 GMT
Connection: keep-alive
So its expected that browser looking at the response of the POST call(401 HTTP code & WWW-Authenticate header) should get prompted to show the native authentication pop up, But it's not doing so. I am not sure what I am doing wrong here. Showing custom form to capture the credential and passing them in "Authorization" header using btoa function is not an option
Appreciate any help, I am ripping my hair apart here!!!
use basic-auth npm plugin
const auth = require('basic-auth');
app.use(function (request, response, next) {
var user = auth(request);
console.log("user => ",user);
if (!user || !user.name || !user.pass) {
response.set('WWW-Authenticate', 'Basic realm="example"');
return response.status(401).send();
}
return next();
});

How to uplaod a file to a multipart post request in ruby

I am trying to upload a file(huge) to a multipart post request in ruby. I use the following code but it gives me 500 internal server error:
RestClient.post("urladdress',
:name_of_file_param => File.new('path_of_the_file_to_be_uploaded'))
Following is the multipart request from the endpoint I am using currently:
POST address HTTP/1.1
Host: ip address
Content-Length: 325
Cache-Control: max-age=0
Origin: http://address
Upgrade-Insecure-Requests: 1
Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryol2BpbpZ9cZlqFyb
User-Agent: blah blah blah
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8
Referer: http://address
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.9
------WebKitFormBoundaryol2BpbpZ9cZlqFyb
Content-Disposition: form-data; name="uploadedFile"; filename="blah.csv"
Content-Type: text/csv
123456789010290
123456789010290
------WebKitFormBoundaryol2BpbpZ9cZlqFyb
Content-Disposition: form-data; name="submit"
Upload APK
------WebKitFormBoundaryol2BpbpZ9cZlqFyb--
Also if someone can help me with creating a new endpoint which can be used to upload the file without using multipart that is fine too.
Thanks,
RV

Preflight request is ok, then, after auth, response does not contain allow cors header

Asp MVC 5 app deployed on IIS 8.5.
Need to enable ajax request from a number of clients.
Server-side I have In WebApiConfig.cs
config.EnableCors();
In controller:
[EnableCors(origins: "http://localhost:59901", headers: "*", methods: "*", SupportsCredentials = true)]
public class ItemController : Controller
Client side
$("#getItem").on("click", function (e) {
var myurl = "http://servername/item/details/1"
$.ajax({
url: myurl,
type: "GET",
dataType: "JSON",
xhrFields: {
withCredentials: true
},
contentType: "application/json; charset=utf-8",
error: function (jqXHR, textStatus, errorThrown) {
$('#result').text(jqXHR.responseText || textStatus);
},
success: function (result) {
$('#result').text(result);
}
});
});
Running client from VisualStudio Origin is http://localhost:59901.
Running the ajax request I get the following in fiddler:
1. Preflight request/response
OPTIONS http://vrtsrv01.webdev.local/item/details/1 HTTP/1.1
Host: vrtsrv01.webdev.local
Connection: keep-alive
Access-Control-Request-Method: GET
Origin: http://localhost:59901
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36
Access-Control-Request-Headers: content-type
Accept: */*
Referer: http://localhost:59901/Home/Index
Accept-Encoding: gzip, deflate, sdch
Accept-Language: en-US,en;q=0.8,it;q=0.6,it-IT;q=0.4
HTTP/1.1 200 OK
Server: Microsoft-IIS/8.5
Access-Control-Allow-Origin: http://localhost:59901
Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, MaxDataServiceVersion
Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS
Access-Control-Allow-Credentials: true
X-Powered-By: ASP.NET
Date: Sat, 13 May 2017 15:34:54 GMT
Content-Length: 0
2. GET request without credentials/ 401 error response
GET http://vrtsrv01.webdev.local/item/details/1 HTTP/1.1
Host: vrtsrv01.webdev.local
Connection: keep-alive
Accept: application/json, text/javascript, */*; q=0.01
Origin: http://localhost:59901
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36
Content-Type: application/json; charset=utf-8
Referer: http://localhost:59901/Home/Index
Accept-Encoding: gzip, deflate, sdch
Accept-Language: en-US,en;q=0.8,it;q=0.6,it-IT;q=0.4
HTTP/1.1 401 Unauthorized
Cache-Control: private
Content-Type: text/html
Server: Microsoft-IIS/8.5
X-AspNet-Version: 4.0.30319
WWW-Authenticate: Negotiate
WWW-Authenticate: NTLM
X-Powered-By: ASP.NET
Date: Sat, 13 May 2017 15:34:54 GMT
Content-Length: 1352
Proxy-Support: Session-Based-Authentication
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"/>
<title>401 - Autorizzazione negata: accesso negato a causa di credenziali non valide.</title>
....
</head>
<body>
<div id="header"><h1>Errore del server</h1></div>
....
</body>
</html>
3. GET request with NTLM token for auth / response without Allow CORS header
GET http://vrtsrv01.webdev.local/item/details/1 HTTP/1.1
Host: vrtsrv01.webdev.local
Connection: keep-alive
Authorization: Negotiate <...NTLM TOKEN HERE ...>
Accept: application/json, text/javascript, */*; q=0.01
Origin: http://localhost:59901
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36
Content-Type: application/json; charset=utf-8
Referer: http://localhost:59901/Home/Index
Accept-Encoding: gzip, deflate, sdch
Accept-Language: en-US,en;q=0.8,it;q=0.6,it-IT;q=0.4
HTTP/1.1 200 OK
Cache-Control: private
Content-Type: application/json; charset=utf-8
Server: Microsoft-IIS/8.5
X-AspNetMvc-Version: 5.2
X-AspNet-Version: 4.0.30319
Persistent-Auth: true
X-Powered-By: ASP.NET
Date: Sat, 13 May 2017 15:34:58 GMT
Content-Length: 8557
{"id":1, .....}
QUESTION
Why after enabling MVC app for CORS and seeing the right response to preflight request, the response obtained after NTLM authentication does not contain the expected Access-Control-Allow-Origin header?
I'm not sure that it will help you, but it might help someone else looking to have both NTLM and CORS enabled.
CORS enabling
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
var corsAttr = new EnableCorsAttribute("*", "*", "*") { SupportsCredentials = true };
//SupportsCredentials = true means that we will add Access-Control-Allow-Credentials to the response.
config.EnableCors(corsAttr);
}
}
SupportsCredentials = true means that we will add Access-Control-Allow-Credentials to the response.
Other solutions,
global.asax.cs - properly reply with headers that allow caller from another domain to receive data
protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
if (Context.Request.HttpMethod == "OPTIONS")
{
Context.Response.AddHeader("Access-Control-Allow-Origin", Context.Request.Headers["Origin"]);
Context.Response.AddHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept,MaxDataServiceVersion");
Context.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
Context.Response.AddHeader("Access-Control-Allow-Credentials", "true");
Context.Response.End();
}
}
SOLVED (...for now...)
The invoked action was a controller action returning Json. This does not work with CORS. I need to create an API controller, cannot use the existing controller. This leads to code duplication, but I have no time now to refactor the whole application to use a single controller both for MVC and API

How to make Flask/ keep Ajax HTTP connection alive?

I have a jQuery Ajax call, like so:
$("#tags").keyup(function(event) {
$.ajax({url: "/terms",
type: "POST",
contentType: "application/json",
data: JSON.stringify({"prefix": $("#tags").val() }),
dataType: "json",
success: function(response) { display_terms(response.terms); },
});
I have a Flask method like so:
#app.route("/terms", methods=["POST"])
def terms_by_prefix():
req = flask.request.json
tlist = terms.find_by_prefix(req["prefix"])
return flask.jsonify({'terms': tlist})
tcpdump shows the HTTP dialog:
POST /terms HTTP/1.1
Host: 127.0.0.1:5000
User-Agent: Mozilla/5.0 (X11; Linux i686; rv:12.0) Gecko/20100101 Firefox/12.0
Accept: application/json, text/javascript, */*; q=0.01
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip, deflate
Connection: keep-alive
Content-Type: application/json; charset=UTF-8
X-Requested-With: XMLHttpRequest
Referer: http://127.0.0.1:5000/
Content-Length: 27
Pragma: no-cache
Cache-Control: no-cache
{"prefix":"foo"}
However, Flask replies without keep-alive.
HTTP/1.0 200 OK
Content-Type: application/json
Content-Length: 445
Server: Werkzeug/0.8.3 Python/2.7.2+
Date: Wed, 09 May 2012 17:55:04 GMT
{"terms": [...]}
Is it really the case that keep-alive is not implemented?
The default request_handler is WSGIRequestHandler.
Before app.run(), Add one line,
WSGIRequestHandler.protocol_version = "HTTP/1.1"
Don't forget from werkzeug.serving import WSGIRequestHandler.
Werkzeug's integrated web server builds on BaseHTTPServer from Python's standard library. BaseHTTPServer seems to support Keep-Alives if you set its HTTP protocol version to 1.1.
Werkzeug doesn't do it but if you're ready to hack into the machinery that Flask uses to instantiate Werkzeug's BaseWSGIServer, you can do it yourself. See Flask.run() which calls werkzeug.serving.run_simple(). What you have to do boils down to BaseWSGIServer.protocol_version = "HTTP/1.1".
I haven't tested the solution. I suppose you do know that Flask's web server ought to be used for development only.

Redirect as response to Ajax request ends up returning empty

We are using Primefaces 3M4 and one of our pages has a p:dataTable which uses ajax calls for events:
<p:ajax event="rowSelect" update=":newsForm:newsDlg" oncomplete="newsDlg.show();"/>
When the session times out the page gets redirected to /login.xhtml which works fine for non-ajax actions (menu items, etc) but when I select a row in the datatable after the session has expired the page doesn't change to the login page and in Firebug I see the following:
Under dashboard.xhtml Headers section of Firebug
Response Headers
Server Apache-Coyote/1.1
X-Powered-By JSF/2.0
Location http://localhost:8080/RetailerPortal/faces/login.xhtml
Content-Length 0
Date Fri, 11 Nov 2011 18:32:42 GMT
Request Headers
Host localhost:8080
User-Agent Mozilla/5.0 (Windows NT 6.1; WOW64; rv:8.0) Gecko/20100101 Firefox/8.0
Accept application/xml, text/xml, */*; q=0.01
Accept-Language en-us,en;q=0.5
Accept-Encoding gzip, deflate
Accept-Charset ISO-8859-1,utf-8;q=0.7,*;q=0.7
Connection keep-alive
Content-Type application/x-www-form-urlencoded; charset=UTF-8
Faces-Request partial/ajax
X-Requested-With XMLHttpRequest
Referer http://localhost:8080/RetailerPortal/faces/dashboard.xhtml
Content-Length 389
Cookie csfcfc=_30Xsr; JSESSIONID=fg1bV1sZkzKIgNtkH0bz0N0f; JSESSIONID=C65BF4EED70299ABFE4B73614118295E
Under dashboard.xhtml Response
<?xml version='1.0' encoding='ISO-8859-1'?>
<partial-response><changes><update id="javax.faces.ViewState"><![CDATA[-3728406524126180805:2441995557020829808]]></update></changes></partial-response>
Under dashbaoard.xhtml Post
Parametersapplication/x-www-form-urlencoded
javax.faces.ViewState 7521050094575005695:7928145831130537413
javax.faces.behavior.even... rowSelect
javax.faces.partial.ajax true
javax.faces.partial.event rowSelect
javax.faces.partial.execu... newsForm:newsTable
javax.faces.partial.rende... newsForm:newsDlg
javax.faces.source newsForm:newsTable
newsForm newsForm
newsForm:newsTable_instan... 3
newsForm:newsTable_select... 3
Source
newsForm=newsForm&newsForm%3AnewsTable_selection=3&javax.faces.ViewState=7521050094575005695%3A7928145831130537413&javax.faces.partial.ajax=true&javax.faces.source=newsForm:newsTable&javax.faces.partial.execute=newsForm:newsTable&javax.faces.partial.render=newsForm:newsDlg&javax.faces.behavior.event=rowSelect&javax.faces.partial.event=rowSelect&newsForm:newsTable_instantSelectedRowKey=3
Under login.xhtml's headers
Response Headers
Server Apache-Coyote/1.1
X-Powered-By JSF/2.0
Cache-Control no-cache
Set-Cookie JSESSIONID=MdhyizD+8IkuFvLZD+6jWlUz; Path=/RetailerPortal
Content-Type text/xml;charset=UTF-8
Content-Length 196
Date Fri, 11 Nov 2011 18:32:42 GMT
Request Headers
Host localhost:8080
User-Agent Mozilla/5.0 (Windows NT 6.1; WOW64; rv:8.0) Gecko/20100101 Firefox/8.0
Accept application/xml, text/xml, */*; q=0.01
Accept-Language en-us,en;q=0.5
Accept-Encoding gzip, deflate
Accept-Charset ISO-8859-1,utf-8;q=0.7,*;q=0.7
Connection keep-alive
Referer http://localhost:8080/RetailerPortal/faces/dashboard.xhtml
X-Requested-With XMLHttpRequest
Faces-Request partial/ajax
Content-Type application/x-www-form-urlencoded
Cookie csfcfc=_30Xsr; JSESSIONID=fg1bV1sZkzKIgNtkH0bz0N0f; JSESSIONID=C65BF4EED70299ABFE4B73614118295E
Under login.xhtml's XML section
XML Parsing Error: no element found Location: moz-nullprincipal:{6ccf85cf-5c69-438c-a9bb-e66423a36a48} Line Number 1, Column 1:
^
Response code
HttpServletResponse servResponse = (HttpServletResponse) response;
servResponse.sendRedirect("login.xhtml");
servResponse.setHeader("Access-Control-Allow-Origin", "*");
Just a guess--
If you're trying to redirect from an ajax response, you can't do that 301/302 style-- you have to send a message back to the browser and have the browser redirect via javascript.
Probably the non-ajax ones are working because they're using 301/302s.
I found the answer to this question in this blog
with the relevant code for at the bottom of the blog post in the doRedirect method.

Resources