Return PDF documents - pdf

I've tried implementing a custom formatter for returning PDF documents from ServiceStack. Without much luck, though. I've looked at the examples and pretty much copied the VCard sample, but replaced it with my code. My formatter looks something like this:
public class PdfFormatter
{
private const string PdfFormatContentType = "application/pdf";
public static void Register(IAppHost appHost)
{
appHost.ContentTypeFilters.Register(PdfFormatContentType, SerializeToStream, (t, s) => { throw new NotImplementedException(); });
}
public static void SerializeToStream(IRequestContext requestcontext, object dto, Stream outputstream)
{
...
}
}
I've called Register from my AppHost and the Content Type Filter is added as expected. My problem is that SerializeToStream is only called when accessing the metadata for my methods. When I call the concrete method on servicestack, an HTML response is returned.
The URL called is: http://mydomain.com/api/pdf/reply/GenerateDocument
The request headers looks like this:
Accept:text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Charset:ISO-8859-1,utf-8;q=0.7,*;q=0.3
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8,da;q=0.6
Cache-Control:max-age=0
Connection:keep-alive
Host:mydomain.com
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.64 Safari/537.31
The response headers look like this:
Cache-Control:private
Connection:Close
Content-Length:46
Content-Type:application/pdf; charset=utf-8
Date:Thu, 16 May 2013 19:59:27 GMT
Server:ASP.NET Development Server/11.0.0.0
X-AspNet-Version:4.0.30319
X-Powered-By:ServiceStack/3,945 Win32NT/.NET
The response is actually PDF but the debugger doesn't break in SerializeToStream.
Any help would be appreciated.

After registering the Content-Type, the client still needs to tell ServiceStack that it wants the PDF content type.
You can do this on the url:
http://example.org/myservice?format=pdf
via a pre-defined route:
http://example.org/pdf/reply/GenerateDocument
Or in the HTTP Accept header, e.g:
GET /myservice
Host: example.org
Accept: application/pdf

Related

WebAPI 2 with OWIN middleware and token-based authentication: OPTIONS request returns "unsupported_grant_type" error

WEbAPI provides end-point for authentication request: http:\...\token
Authentication request should be sent using Method "POST" and Body like
"grant_type=password&username=name&password=mypassword"
This WebAPI is used by Front-End which is written using AngularJS.
Sometimes before sending "POST" request with valid Body, a "OPTIONS" request is sent without Body.
As result the following error is returned by WebAPI:
Status: 400
{"error":"unsupported_grant_type"}
Is there any solution which can be implemented on Server-side? (in WebAPI)
HTTP Request Method: OPTIONS
Request Header:
Accept:*/*
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8,de;q=0.6,ru;q=0.4,uk;q=0.2
Access-Control-Request-Headers:accept, authorization, content-type
Access-Control-Request-Method:POST
Cache-Control:no-cache
Host:...
Origin:...
Pragma:no-cache
Proxy-Connection:keep-alive
Referer:...
User-Agent:Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.120 Safari/537.36
Response Header:
Cache-Control: no-cache
Pragma: no-cache
Content-Length: 34
Content-Type: application/json;charset=UTF-8
Expires: -1
Server: Microsoft-IIS/7.5
Access-Control-Allow-Origin: *
X-Powered-By: ASP.NET
Date: Thu, 11 Sep 2014 18:05:09 GMT
I just ran into the same issue..I'm using ember and ember-simple-auth. Any preflight requests OPTIONS to the /token endpoint were resulting in a 400 HTTP response and the body had the well known: {error: "unsuported_grant_type"}.
SOLUTION:
I inherit from: OAuthAuthorizationServerProvider and override the MatchEndpoint function:
public override Task MatchEndpoint(OAuthMatchEndpointContext context)
{
if (context.OwinContext.Request.Method == "OPTIONS" && context.IsTokenEndpoint)
{
context.OwinContext.Response.Headers.Add("Access-Control-Allow-Methods", new[] {"POST"});
context.OwinContext.Response.Headers.Add("Access-Control-Allow-Headers", new[] { "accept", "authorization", "content-type" });
context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
context.OwinContext.Response.StatusCode = 200;
context.RequestCompleted();
return Task.FromResult<object>(null);
}
return base.MatchEndpoint(context); }
That seems to take care of it. Hope it helps.
I got the same error when I forgot to add Content-Type: application/x-www-form-urlencoded to the request header.
I was attempting to test my api with Fiddler and wasn't providing the data in the correct format in the Request Body section. Be sure it's added as a key value list separated by '&'.
grant_type=password&username=testUsername&password=testPassword
In this case OPTIONS is a CORS preflight request. It is sent in order to determine whether the actual request (POST) is safe to send. Cross-site requests are preflighted if uses methods other than GET, HEAD or POST or sets custom headers.
In order to avoid a 400 HTTP response, in your Startup class you should enable CORS for the OWIN middleware using UseCors extension method and define your custom System.Web.Cors.CorsPolicy.
using Microsoft.Owin.Cors;
using Microsoft.Owin.Security.OAuth;
using Owin;
namespace AuthorizationServer
{
public partial class Startup
{
public void ConfigureAuth(IAppBuilder app)
{
app.UseCors(CorsOptions.AllowAll);
app.UseOAuthAuthorizationServer(new OAuthAuthorizationServerOptions()
{
});
}
}
}

ember-simple-auth oauth2 authorizer issue

I am trying to set up authorization on an Ember App running on a Node.js server.
I am using the oauth2 Authenticator, which is requesting a token from the server. This is working fine. I am able to provide the app with a token, which it saves in the local-storage.
However, when I make subsequent requests, the authorizer is not adding the token to the header, I have initialized the authorizer using the method described in the documentation (http://ember-simple-auth.simplabs.com/ember-simple-auth-oauth2-api-docs.html):
Ember.Application.initializer({
name: 'authentication',
initialize: function(container, application) {
Ember.SimpleAuth.setup(container, application, {
authorizerFactory: 'authorizer:oauth2-bearer'
});
}
});
var App = Ember.Application.create();
And I have added an init method to the Authorizer, to log a message to the server when it is initialized, so I know that it is being loaded. The only thing is, the authorize method of the authorizer is never called.
It feels like I am missing a fundamental concept of the library.
I have a users route which I have protected using the AuthenticatedRouteMixin like so:
App.UsersRoute = Ember.Route.extend(Ember.SimpleAuth.AuthenticatedRouteMixin, {
model: function() {
return this.get('store').find('user');
}
});
Which is fetching the data, fine, and redirects to /login if no token is in the session, but the request headers do not include the token:
GET /users HTTP/1.1
Host: *****
Connection: keep-alive
Cache-Control: no-cache
Pragma: no-cache
Accept: application/json, text/javascript, */*; q=0.01
Origin: *****
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.116 Safari/537.36
Referer: *****
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8
Any help you could give me would be greatly appreciated.
Is your REST API served on a different origin than the app is loaded from maybe? Ember.SimpleAuth does not authorizer cross origin requests by default (see here: https://github.com/simplabs/ember-simple-auth#cross-origin-authorization)

How to post int array using $http to a ASP.Net Web Api Controller method

I am trying to post an array of integers to delete from a service using $http to ASP.Net Web API controller method. I have tried both
[HttpDelete]
public HttpResponseMessage DeleteMany(int[] ids) { }
[HttpDelete]
public HttpResponseMessage DeleteMany(DeleteManyDto dto) { }
public class DeleteManyDto
{
public int[] Ids {get;set;}
}
I keep getting the params as null. I have tried a couple of variations in the Angular service. Here is an example
this.deleteMany = function(ids) {
// ids is an int array. e.g. [1,4,6]
return $http.delete('api/Foo/DeleteMany', { toDelete: ids }).then(function(result) {
return result.status;
});
};
Anyone know what I could be missing?
UPDATE: Spelling mistake. Included debug from HTTP request.
Request URL:http://localhost:54827/api/Foo/DeleteMany
Request Method:DELETE
Status Code:500 Internal Server Error
Request Headersview source
Accept:application/json, text/plain, */*
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8
Cache-Control:no-cache
Connection:keep-alive
Cookie:__RequestVerificationToken=blabla
Host:localhost:54827
Origin:http://localhost:54827
Pragma:no-cache
Referer:http://localhost:54827/
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.101 Safari/537.36
Response Headersview source
The code above is not producing any request payload. When I do an update I see the request payload. Example
Request Payloadview parsed
{"id":4,"name":"zzzz", "bar": 2}
For what it is worth I am using Angular 1.2.rc3
Try changing your controller method signature to this:
[HttpDelete]
public HttpResponseMessage DeleteMany(int[] toDelete) { }
or if you using your ViewModel than change delete call to this:
return $http.delete('api/Foo/DeleteMany', { Ids: ids }).then(function(result) {
return result.status;
});
Edit:
But I think that real problem is in $http.delete call. You can't send body with DELETE verb in HTTP, and because MVC binds data from message body or url your array is not binded.
Try implement DeleteMany with POST request.
http://docs.angularjs.org/api/ng.$http#methods_delete
You see that in documentation delete method doesn't have data param in its definition.
Or you can try this approach, where you add your data to message header:
What is a clean way to send a body with DELETE request?
You have a spelling error in your API:
public HttpResponseMessage DeleteManay(int[] ids) { }
should be:
public HttpResponseMessage DeleteMany(int[] ids) { }
Update:
Appears it was a spelling mistake in the question.

CORS request is preflighted, but it seems like it should not be

The following cross-origin POST request, with a content-type of multipart/form-data and only simple headers is preflighted. According to the W3C spec, unless I am reading it wrong, it should not be preflighted. I've confirmed this happens in Chrome 27 and Firefox 10.8.3. I haven't tested any other browsers.
Here are the request headers, etc:
Request URL:http://192.168.130.135:8081/upload/receiver
Request Method:POST
Status Code:200 OK
Request Headersview source
Accept:*/*
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8
Connection:keep-alive
Content-Length:27129
Content-Type:multipart/form-data; boundary=----WebKitFormBoundaryix5VzTyVtCMwcNv6
Host:192.168.130.135:8081
Origin:http://192.168.130.135:8080
Referer:http://192.168.130.135:8080/test/raytest-jquery.html
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.37 Safari/537.36
And here is the OPTIONS (preflight) request:
Request URL:http://192.168.130.135:8081/upload/receiver
Request Method:OPTIONS
Status Code:200 OK
Request Headersview source
Accept:*/*
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8
Access-Control-Request-Headers:origin, content-type
Access-Control-Request-Method:POST
Connection:keep-alive
Host:192.168.130.135:8081
Origin:http://192.168.130.135:8080
Referer:http://192.168.130.135:8080/test/raytest-jquery.html
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.37 Safari/537.36
The spec seems pretty clear:
Only simple headers: CHECK
Only simple methods: CHECK
UPDATE: Here's some simple client-side code that will reproduce this:
var xhr = new XMLHttpRequest(),
formData = new FormData();
formData.append('myfile', someFileObj);
xhr.upload.progress = function(e) {
//insert upload progress logic here
};
xhr.open('POST', 'http://192.168.130.135:8080/upload/receiver', true);
xhr.send(formData);
Does anyone know why this is being preflighted?
I ended up checking out the Webkit source code in an attempt to figure this out (after Google did not yield any helpful hits). It turns out that Webkit will force any cross-origin request to be preflighted simply if you register an onprogress event handler. I'm not entirely sure, even after reading the code comments, why this logic was applied.
In XMLHttpRequest.cpp:
void XMLHttpRequest::createRequest(ExceptionCode& ec)
{
...
options.preflightPolicy = uploadEvents ? ForcePreflight : ConsiderPreflight;
...
// The presence of upload event listeners forces us to use preflighting because POSTing to an URL that does not
// permit cross origin requests should look exactly like POSTing to an URL that does not respond at all.
// Also, only async requests support upload progress events.
bool uploadEvents = false;
if (m_async) {
m_progressEventThrottle.dispatchEvent(XMLHttpRequestProgressEvent::create(eventNames().loadstartEvent));
if (m_requestEntityBody && m_upload) {
uploadEvents = m_upload->hasEventListeners();
m_upload->dispatchEvent(XMLHttpRequestProgressEvent::create(eventNames().loadstartEvent));
}
}
...
}
UPDATE: Firefox applies the same logic as Webkit, it appears. Here is the relevant code from nsXMLHttpRequest.cpp:
nsresult
nsXMLHttpRequest::CheckChannelForCrossSiteRequest(nsIChannel* aChannel)
{
...
// Check if we need to do a preflight request.
nsCOMPtr<nsIHttpChannel> httpChannel = do_QueryInterface(aChannel);
NS_ENSURE_TRUE(httpChannel, NS_ERROR_DOM_BAD_URI);
nsAutoCString method;
httpChannel->GetRequestMethod(method);
if (!mCORSUnsafeHeaders.IsEmpty() ||
(mUpload && mUpload->HasListeners()) ||
(!method.LowerCaseEqualsLiteral("get") &&
!method.LowerCaseEqualsLiteral("post") &&
!method.LowerCaseEqualsLiteral("head"))) {
mState |= XML_HTTP_REQUEST_NEED_AC_PREFLIGHT;
}
...
}
Notice the mUpload && mUpload->HasListeners() portion of the conditional.
Seems like Webkit and Firefox (and possibly others) have inserted some logic into their preflight-determination code that is not sanctioned by the W3C spec. If I'm missing something in the spec, please comment.
My guess is that the "boundary" on the Content-Type header is causing issues. If you are able to reproduce this, it should be filed as a browser bug, since the spec states that the Content-Type header check should exclude parameters.

Deserialize Key:Value pairs to Dictionary

I am working on deserializing data passed to a Microsoft Web API in MVC4 RC into objects of the following class:
public class EditorCreateEditSubmission
{
public string action { get; set; }
public string table { get; set; }
public string id { get; set; }
public Dictionary<string, string> data { get; set; }
}
Whenever a Web API method gets data which should map to the EditorCreateEditSubmission, the "data" field is empty, like so:
(It's okay for Table and ID to be empty)
My controller method:
public EditorServerResponse Post(EditorCreateEditSubmission ajaxSubmission)
{
//...Handle data
}
The raw header:
POST http://localhost:64619/API/Species HTTP/1.1
Accept: application/json, text/javascript, */*; q=0.01
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
X-Requested-With: XMLHttpRequest
Referer: http://localhost:64619/Manage/Species
Accept-Language: en-us
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)
Host: localhost:64619
Content-Length: 134
Connection: Keep-Alive
Pragma: no-cache
action=create&table=&id=&data%5Bamu%5D=1&data%5BchemicalFormula%5D=H&data%5BcommonName%5D=Hydrogen&data%5Bstatus%5D=N&data%5Bnotes%5D=
More readable view:
action create
table
id
data[amu] 1
data[chemicalFormula] H
data[commonName] Hydrogen
data[status] N
data[notes]
Do I need to manually create a class with get/set values every possible set of incoming values? It seems like deserialization of this data into a Dictionary should be straightforward, but I'm having some difficulty finding examples inthe new RC release of Microsoft's MVC4.
I don't think that the FormUrlEncodedMediaTypeFormatter does handle this.