Authenticated WCF Data Service through Azure Service Bus - azure

I'm stuck on this. I have a WCF Data Service that successfully creates an HTTPS endpoint in the Azure Service Bus.
I originally set the service up for testing using <security relayClientAuthenticationType="None" /> and I was able to consume the service just fine in a client.
The data going through this service will be sensitive, however, so to lock it down I switched to <security relayClientAuthenticationType="RelayAccessToken" /> in the Web.Config file of the service.
I am using the following code to obtain my token:
static string GetToken(string serviceNamespace, string issuerName, string issuerPassword)
{
if (_token == null)
{
string acsEndpoint = "https://" + serviceNamespace + "-sb.accesscontrol.windows.net/WRAPv0.9";
string relyingPartyAddress = "http://" + serviceNamespace + ".servicebus.windows.net";
NameValueCollection postData = new NameValueCollection
{
{ "wrap_scope", relyingPartyAddress },
{ "wrap_name", issuerName },
{ "wrap_password", issuerPassword },
};
WebClient webClient = new WebClient();
byte[] responseBuffer = webClient.UploadValues(acsEndpoint, "POST", postData);
string response = Encoding.UTF8.GetString(responseBuffer);
response = Uri.UnescapeDataString(response);
string[] tokenVariables = response.Split('&');
int tokenIndex = Array.FindIndex(tokenVariables, s => s.StartsWith("HMACSHA256"));
string[] tokenVariable = tokenVariables[tokenIndex].Split('=');
_token = HttpUtility.UrlDecode(tokenVariable[1]);
}
return _token;
}
static string _token = null;
And then I use context.SendingRequest += new EventHandler<SendingRequestEventArgs>(OnSendingRequest); and the following to add my token to the header of my REST request:
static void OnSendingRequest(object sender, SendingRequestEventArgs e)
{
e.RequestHeaders.Add(
"Authorization",
string.Format("WRAP access_token=\"{0}\"", GetToken("MyNamespace", "owner", "MySecret") )
);
}
And then my request takes the following form (Which worked perfectly before the security was added)
try
{
var results = (from b in context.Banks where b.Bank1 != "Bank1" select b).Take(200).ToList();
ViewBag.Results = results;
}
catch (DataServiceQueryException ex)
{
ViewBag.Message = "Authentication failed. A new token will be requested.";
var code = ex.Response.StatusCode;
if (code == 401)
_token = null;
}
While I was developing the code to get and attach the token I ran in to plenty of token errors, so I believe that I am successfully getting a token now, but now I get the following error:
500TrackingId:38940805-f9b3-4444-a8e3-2a00b2309cf6_G0, Timestamp:11/11/2012 11:48:33 AM
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Data.Services.Client.DataServiceClientException: 500TrackingId:38940805-f9b3-4444-a8e3-2a00b2309cf6_G0, Timestamp:11/11/2012 11:48:33 AM
Source Error:
Line 31: context.SendingRequest += new EventHandler(OnSendingRequest);
Line 32:
Line 33: var results = (from b in context.Banks where b.Bank1 != "Bank1" select b).Take(200).ToList();
Line 34:
Line 35: try
Source File: c:\Users\v-tadam.REDMOND\Documents\Visual Studio 2012\Projects\CFARPOC\CFARPOCClient\Controllers\HomeController.cs Line: 33
Stack Trace:
[DataServiceClientException: 500TrackingId:38940805-f9b3-4444-a8e3-2a00b2309cf6_G0, Timestamp:11/11/2012 11:48:33 AM]
System.Data.Services.Client.QueryResult.Execute() +414618
System.Data.Services.Client.DataServiceRequest.Execute(DataServiceContext context, QueryComponents queryComponents) +131
[DataServiceQueryException: An error occurred while processing this request.]
System.Data.Services.Client.DataServiceRequest.Execute(DataServiceContext context, QueryComponents queryComponents) +432
System.Data.Services.Client.DataServiceQuery`1.Execute() +77
System.Data.Services.Client.DataServiceQuery`1.GetEnumerator() +13
System.Collections.Generic.List`1..ctor(IEnumerable`1 collection) +369
System.Linq.Enumerable.ToList(IEnumerable`1 source) +58
CFARPOCClient.Controllers.HomeController.Banks() in c:\Users\v-tadam.REDMOND\Documents\Visual Studio 2012\Projects\CFARPOC\CFARPOCClient\Controllers\HomeController.cs:33
lambda_method(Closure , ControllerBase , Object[] ) +101
System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +14
System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +211
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +27
System.Web.Mvc.Async.c__DisplayClass42.b__41() +28
System.Web.Mvc.Async.c__DisplayClass8`1.b__7(IAsyncResult _) +10
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +57
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +48
System.Web.Mvc.Async.c__DisplayClass39.b__33() +57
System.Web.Mvc.Async.c__DisplayClass4f.b__49() +223
System.Web.Mvc.Async.c__DisplayClass37.b__36(IAsyncResult asyncResult) +10
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +57
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +48
System.Web.Mvc.Async.c__DisplayClass2a.b__20() +24
System.Web.Mvc.Async.c__DisplayClass25.b__22(IAsyncResult asyncResult) +102
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +57
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +43
System.Web.Mvc.c__DisplayClass1d.b__18(IAsyncResult asyncResult) +14
System.Web.Mvc.Async.c__DisplayClass4.b__3(IAsyncResult ar) +23
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +57
System.Web.Mvc.Async.c__DisplayClass4.b__3(IAsyncResult ar) +23
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62
System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +47
System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +10
System.Web.Mvc.c__DisplayClass8.b__3(IAsyncResult asyncResult) +25
System.Web.Mvc.Async.c__DisplayClass4.b__3(IAsyncResult ar) +23
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +47
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9629708
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155
This error is not helping me find the problem. What am I doing wrong? Consuming the service worked flawlessly before the security was implemented, and I've done all the research I can in to how to get the token and attach it to my request. Does anything jump out that I have done incorrectly?

I found my mistake. I had a fundamental misunderstanding of what constituted the token. For some reason I got it in my head that it was the text that followed "HMACSHA256" when in fact the token was everything in the response that follows "wrap_access_token=" (which seems obvious now...)
Anyway, if anyone else has this issue, the 500 error code is being thrown because the token is being correctly retrieved but the wrong token is being added to the request header. I tested this by attaching "GARBAGETOKEN" and observing the same behavior.
The following is a valid GetToken method:
static string GetToken(string serviceNamespace, string issuerName, string issuerPassword)
{
if (_token == null)
{
string acsEndpoint = "https://" + serviceNamespace + "-sb.accesscontrol.windows.net/WRAPv0.9";
string relyingPartyAddress = "http://" + serviceNamespace + ".servicebus.windows.net";
NameValueCollection postData = new NameValueCollection
{
{ "wrap_scope", relyingPartyAddress },
{ "wrap_name", issuerName },
{ "wrap_password", issuerPassword },
};
WebClient webClient = new WebClient();
byte[] responseBuffer = webClient.UploadValues(acsEndpoint, "POST", postData);
string response = Encoding.UTF8.GetString(responseBuffer);
string token = response.Split('&')
.Single(value => value.StartsWith("wrap_access_token=") )
.Split('=')[1];
_token = HttpUtility.UrlDecode(token);
}
return _token;
}
static string _token = null;
Hopefully my folly helps someone else :)

Related

How to fix 'The DocumentName value is not specified.' Even if DocumentName property is already supplied

I'm using the DancingGoatMVC sample of Kentico.
Now I'm testing if I can add an Article page using the api.
Basically I added new method to the article controller and views.
As you can see I'm already populating the DocumentName but the error is still occurring, any ideas to solve this error and what I might be missing that is causing this issue?
Thanks
Controllers:
public ActionResult Add()
{
return View();
}
[HttpPost]
public ActionResult Add(ArticleViewModel articleViewModel)
{
// Creates a new instance of the Tree provider
TreeProvider tree = new TreeProvider(MembershipContext.AuthenticatedUser);
// Gets the current site's root "/" page, which will serve as the parent page
TreeNode parentPage = tree.SelectNodes()
.Path("/Articles")
.OnCurrentSite()
.Culture("en-us")
.FirstObject;
if (parentPage.DocumentName != null)
{
TreeNode newPage = TreeNode.New(SystemDocumentTypes.Root,
tree);
// Sets the properties of the new page
newPage.DocumentName = "Articles";
newPage.DocumentCulture = "en-us";
newPage.SetValue("Title", "test");
newPage.SetValue("Summary", "test");
newPage.SetValue("Text", "test");
newPage.SetValue("DocumentName", "Articles");
// Inserts the new page as a child of the parent page
newPage.Insert(parentPage,true);
}
return RedirectToAction("Index");
}
Error:
Server Error in '/Kentico12_DancingGoatMvc' Application.
The DocumentName value is not specified.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Exception: The DocumentName value is not specified.
Source Error:
Line 90: newPage.SetValue("DocumentName", "Articles");
Line 91: // Inserts the new page as a child of the parent page
Line 92: newPage.Insert(parentPage,true);
Line 93: }
Line 94:
Source File: C:\inetpub\wwwroot\Kentico12\DancingGoatMvc\Controllers\ArticlesController.cs Line: 92
Stack Trace:
[Exception: The DocumentName value is not specified.]
CMS.DocumentEngine.TreeNode.InsertNode(TreeNode parent) in D:\CMS\MAIN\CMSSolution\DocumentEngine\Documents\TreeNode.cs:4008
CMS.DocumentEngine.TreeNode.Insert(TreeNode parent, Boolean useDocumentHelper) in D:\CMS\MAIN\CMSSolution\DocumentEngine\Documents\TreeNode.cs:3959
CMS.DocumentEngine.DocumentHelper.InsertDocument(TreeNode node, TreeNode parentNode, TreeProvider tree, Boolean allowCheckOut) in D:\CMS\MAIN\CMSSolution\DocumentEngine\DocumentHelper.cs:457
CMS.DocumentEngine.TreeNode.Insert(TreeNode parent, Boolean useDocumentHelper) in D:\CMS\MAIN\CMSSolution\DocumentEngine\Documents\TreeNode.cs:3946
DancingGoat.Controllers.ArticlesController.Add(ArticleViewModel articleViewModel) in C:\inetpub\wwwroot\Kentico12\DancingGoatMvc\Controllers\ArticlesController.cs:92
lambda_method(Closure , ControllerBase , Object[] ) +139
System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary2 parameters) +229
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary2 parameters) +35
System.Web.Mvc.Async.AsyncControllerActionInvoker.b__39(IAsyncResult asyncResult, ActionInvocation innerInvokeState) +39
System.Web.Mvc.Async.WrappedAsyncResult2.CallEndDelegate(IAsyncResult asyncResult) +77
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +42
System.Web.Mvc.Async.AsyncInvocationWithFilters.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3d() +72
System.Web.Mvc.Async.<>c__DisplayClass46.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f() +387
System.Web.Mvc.Async.<>c__DisplayClass46.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f() +387
System.Web.Mvc.Async.<>c__DisplayClass46.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f() +387
System.Web.Mvc.Async.<>c__DisplayClass46.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f() +387
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +42
System.Web.Mvc.Async.<>c__DisplayClass2b.<BeginInvokeAction>b__1c() +38
System.Web.Mvc.Async.<>c__DisplayClass21.<BeginInvokeAction>b__1e(IAsyncResult asyncResult) +188
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +38
System.Web.Mvc.Controller.<BeginExecuteCore>b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState) +29
System.Web.Mvc.Async.WrappedAsyncVoid1.CallEndDelegate(IAsyncResult asyncResult) +73
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +52
System.Web.Mvc.Async.WrappedAsyncVoid1.CallEndDelegate(IAsyncResult asyncResult) +39
System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +38
System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__5(IAsyncResult asyncResult, ProcessRequestState innerState) +43
System.Web.Mvc.Async.WrappedAsyncVoid1.CallEndDelegate(IAsyncResult asyncResult) +73
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +38
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +602
System.Web.HttpApplication.ExecuteStepImpl(IExecutionStep step) +195
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +128
This line here appears to be the problem:
newPage.SetValue("DocumentName", "Articles")
Why are you assigning it like this when you're already assigning it above?
Secondly, is your DocumentName property based on another required property of the page type like Title? You can see this under the Fields definition of the page type. The dropdown will be directly under the Field names box.

What is causing the "Error calling CreateEnvelope - TAB_REFERS_TO_MISSING_DOCUMENT" error when creating composite envelope?

I have the following code that is supposed to send an envelope with multiple templates to sign:
public void SendEvelope(List<string> templateIds)
{
var envelope = new EnvelopeDefinition { EmailSubject = "Please sign this", Status = "created", CompositeTemplates = new List<CompositeTemplate>() };
var ct = new CompositeTemplate { ServerTemplates = new List<ServerTemplate>(), InlineTemplates = new List<InlineTemplate>() };
foreach (var templateId in templateIds)
{
var template = _templatesApi.Get(AccountId, templateId);
if (template == null) continue;
ct.ServerTemplates.Add(new ServerTemplate { TemplateId = templateId, Sequence = "1" });
var it = new InlineTemplate
{
Sequence = "1",
Recipients = new Recipients { Signers = new List<Signer>() }
};
var signer = new Signer
{
Name = "John Doe",
Email = "me#here.com",
RoleName = "Client",
RecipientId = "1"
};
it.Recipients.Signers.Add(signer);
ct.InlineTemplates.Add(it);
envelope.CompositeTemplates.Add(ct);
}
_envelopesApi.CreateEnvelope(AccountId, envelope);
}
The code seems to be working properly until it gets to the CreateEnvelope command at which point it crashes with the following error:
Error calling CreateEnvelope: { "errorCode":
"TAB_REFERS_TO_MISSING_DOCUMENT", "message": "The DocumentId specified in
the tab element does not refer to a document in this envelope. Tab refers
to DocumentId 54017690 which is not present." }
I am not specifying any tabs or documents in my call and each template I am adding to the envelope exists for sure since they are being fetched one at a time from the API. So what is the problem here? What am I missing?
EDIT:
Here is the full stack trace:
DocuSign.eSign.Client.ApiException: Error calling CreateEnvelope: {
"errorCode": "TAB_REFERS_TO_MISSING_DOCUMENT",
"message": "The DocumentId specified in the tab element does not refer to a document in this envelope. Tab refers to DocumentId 54017690 which is not present."
}
at DocuSign.eSign.Api.EnvelopesApi.CreateEnvelopeWithHttpInfo(String accountId, EnvelopeDefinition envelopeDefinition, CreateEnvelopeOptions options) in y:\Docusign\Github\DevCenter\SDKs\csharp\sdk\src\main\csharp\DocuSign\eSign\Api\EnvelopesApi.cs:line 2606
at DocuSign.eSign.Api.EnvelopesApi.CreateEnvelope(String accountId, EnvelopeDefinition envelopeDefinition, CreateEnvelopeOptions options) in y:\Docusign\Github\DevCenter\SDKs\csharp\sdk\src\main\csharp\DocuSign\eSign\Api\EnvelopesApi.cs:line 2532
at LeadDocket.Core.Services.DocuSignService.SendEvelope(List`1 templateIds, Int32 leadId, Settings settings) in C:\inetpub\Websites\LeadDocket\Source\LeadDocket.Core\Services\DocuSignService.cs:line 64
at LeadDocket.Website.Controllers.LeadsController.PickTemplates(PickTemplatesViewModel model) in C:\inetpub\Websites\LeadDocket\Source\LeadDocket.Website\Controllers\LeadsController.cs:line 638
at lambda_method(Closure , ControllerBase , Object[] )
at System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters)
at System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters)
at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.<BeginInvokeSynchronousActionMethod>b__39(IAsyncResult asyncResult, ActionInvocation innerInvokeState)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`2.CallEndDelegate(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase`1.End()
at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3d()
at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<>c__DisplayClass46.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f()
at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass33.<BeginInvokeActionMethodWithFilters>b__32(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase`1.End()
at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass21.<>c__DisplayClass2b.<BeginInvokeAction>b__1c()
at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass21.<BeginInvokeAction>b__1e(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase`1.End()
at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult)
at System.Web.Mvc.Controller.<BeginExecuteCore>b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase`1.End()
at System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult)
at System.Web.Mvc.Controller.<BeginExecute>b__15(IAsyncResult asyncResult, Controller controller)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase`1.End()
at System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult)
at System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult)
at System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__5(IAsyncResult asyncResult, ProcessRequestState innerState)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase`1.End()
at System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult)
at System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result)
at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
EDIT 2:
Here is what I get in the log:
POST https://demo.docusign.net:7801/restapi/v2/accounts/1661307/envelopes
Content-Length: 2148
Content-Type: application/json
Accept: application/json
Host: demo.docusign.net
User-Agent: RestSharp/100.0.0.0
X-DocuSign-SDK: C#
X-DocuSign-Authentication: {"Username":"mmijuskovic#somedomain.com", "Password":"[omitted]", "IntegratorKey":"[omitted]"}
X-Forwarded-For: 157.182.105.1
X-SecurityProtocol-Version: TLSv1
X-SecurityProtocol-CipherSuite: ECDHE-RSA-AES256-CBC-SHA
{"compositeTemplates":[{"serverTemplates":[{"sequence":"1","templateId":"3639308e-778d-46bf-9f82-04834166a2a6"},{"sequence":"1","templateId":"50c95d3c-0d55-4dca-924c-73dbf1437b27"},{"sequence":"1","templateId":"98960d61-f3e5-4fda-958c-122b972eecdd"}],"inlineTemplates":[{"sequence":"1","recipients":{"signers":[{"name":"Heather M. Batz","email":"me#here.com","recipientId":"1","roleName":"Client"}]}},{"sequence":"1","recipients":{"signers":[{"name":"Heather M. Batz","email":"me#here.com","recipientId":"1","roleName":"Client"}]}},{"sequence":"1","recipients":{"signers":[{"name":"Heather M. Batz","email":"me#here.com","recipientId":"1","roleName":"Client"}]}}]},{"serverTemplates":[{"sequence":"1","templateId":"3639308e-778d-46bf-9f82-04834166a2a6"},{"sequence":"1","templateId":"50c95d3c-0d55-4dca-924c-73dbf1437b27"},{"sequence":"1","templateId":"98960d61-f3e5-4fda-958c-122b972eecdd"}],"inlineTemplates":[{"sequence":"1","recipients":{"signers":[{"name":"Heather M. Batz","email":"me#here.com","recipientId":"1","roleName":"Client"}]}},{"sequence":"1","recipients":{"signers":[{"name":"Heather M. Batz","email":"me#here.com","recipientId":"1","roleName":"Client"}]}},{"sequence":"1","recipients":{"signers":[{"name":"Heather M. Batz","email":"me#here.com","recipientId":"1","roleName":"Client"}]}}]},{"serverTemplates":[{"sequence":"1","templateId":"3639308e-778d-46bf-9f82-04834166a2a6"},{"sequence":"1","templateId":"50c95d3c-0d55-4dca-924c-73dbf1437b27"},{"sequence":"1","templateId":"98960d61-f3e5-4fda-958c-122b972eecdd"}],"inlineTemplates":[{"sequence":"1","recipients":{"signers":[{"name":"Heather M. Batz","email":"me#here.com","recipientId":"1","roleName":"Client"}]}},{"sequence":"1","recipients":{"signers":[{"name":"Heather M. Batz","email":"me#here.com","recipientId":"1","roleName":"Client"}]}},{"sequence":"1","recipients":{"signers":[{"name":"Heather M. Batz","email":"me#here.com","recipientId":"1","roleName":"Client"}]}}]}],"status":"sent","emailSubject":"Local Firm - Please sign this"}
400 BadRequest
Content-Type: application/json; charset=utf-8
{
"errorCode": "TAB_REFERS_TO_MISSING_DOCUMENT",
"message": "The DocumentId specified in the tab element does not refer to a document in this envelope. Tab refers to DocumentId 54017690 which is not present."
}

MVC5 AntiForgeryToken Claims/"Sequence contains more than one element"

Case: I have an MVC5 application (basically the MVC5 template with a scaffolded view) with the Google authentication method enabled. The application has been configured to accept email as user name and to store the claims assigned from Google like Surname, givenname, email, nameidentifier, etc, to the membership database (AspNetUserClaims).
When I register and log in with a "local" user everything is fine.
If I log in with a Google user its fine.
If I log in with an account set up to have both a local and external login I get the error below.
I have tried changing the type for the token to different settings using the AntiForgeryConfig option in Application_Start (example)
AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.Email;
But it seems all the Claims are duplicated when combining local and external logins. The strangest thing is that the claims-collection (which I assumed had the answer) is identical for the combined and the external only login.
When logged in as local user these Claims are assigned
[0]: {http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier: a71ff9c0-8dc4-478b-a6f1-2c4cc34b1e46}
[1]: {http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name: some#email.com}
[2]: {http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider: ASP.NET Identity}
When logged in with a remote-only or a combined account the claims-list looks like this
[0]: {http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier: 4ab33d77-c2a0-4eff-a759-5cca4323ecbf}
[1]: {http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name: some.other#email.com}
[2]: {http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider: ASP.NET Identity}
[3]: {http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier: https://www.google.com/accounts/o8/id?id=AitOGoogleIdentifierRemovedForPrivacygwgwgw}
[4]: {http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress: some.other#email.com}
[5]: {http://schemas.xmlsoap.org/ws/2005/05/identity/claims/surname: Other}
[6]: {http://schemas.xmlsoap.org/ws/2005/05/identity/claims/givenname: Some}
[7]: {http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name: Some Other Person}
Any help will be much appreciated!
Error and stacktrace follows:
Server Error in '/' Application.
Sequence contains more than one matching element
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.InvalidOperationException: Sequence contains more than one matching element
Source Error:
Line 10: #using (Html.BeginForm())
Line 11: {
Line 12: #Html.AntiForgeryToken()
Line 13:
Line 14: <div class="form-horizontal">
Source File: x:\someweb\Views\someEntity\Create.cshtml Line: 12
Stack Trace:
[InvalidOperationException: Sequence contains more than one matching element]
System.Linq.Enumerable.SingleOrDefault(IEnumerable`1 source, Func`2 predicate) +2533810
System.Web.Helpers.AntiXsrf.ClaimUidExtractor.GetUniqueIdentifierParameters(ClaimsIdentity claimsIdentity, String uniqueClaimTypeIdentifier) +701
System.Web.Helpers.AntiXsrf.ClaimUidExtractor.ExtractClaimUid(IIdentity identity) +186
System.Web.Helpers.AntiXsrf.TokenValidator.GenerateFormToken(HttpContextBase httpContext, IIdentity identity, AntiForgeryToken cookieToken) +242
System.Web.Helpers.AntiXsrf.AntiForgeryWorker.GetTokens(HttpContextBase httpContext, AntiForgeryToken oldCookieToken, AntiForgeryToken& newCookieToken, AntiForgeryToken& formToken) +174
System.Web.Helpers.AntiXsrf.AntiForgeryWorker.GetFormInputElement(HttpContextBase httpContext) +109
System.Web.Helpers.AntiForgery.GetHtml() +146
System.Web.Mvc.HtmlHelper.AntiForgeryToken() +39
ASP._Page_Views_Bruker_Create_cshtml.Execute() in x:\prosjekter\Laudi\TFS\Laudi\IWeb\Inspector\Inspector\Views\Bruker\Create.cshtml:12
System.Web.WebPages.WebPageBase.ExecutePageHierarchy() +271
System.Web.Mvc.WebViewPage.ExecutePageHierarchy() +120
System.Web.WebPages.StartPage.RunPage() +63
System.Web.WebPages.StartPage.ExecutePageHierarchy() +100
System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage) +131
System.Web.Mvc.RazorView.RenderView(ViewContext viewContext, TextWriter writer, Object instance) +695
System.Web.Mvc.BuildManagerCompiledView.Render(ViewContext viewContext, TextWriter writer) +382
System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context) +431
System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext controllerContext, ActionResult actionResult) +39
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult) +116
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult) +529
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult) +106
System.Web.Mvc.Async.<>c__DisplayClass28.<begininvokeaction>
b__19() +321
System.Web.Mvc.Async.<>c__DisplayClass1e.<begininvokeaction>
b__1b(IAsyncResult asyncResult) +185
System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +42
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +133
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +56
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +40
System.Web.Mvc.Controller.<beginexecutecore>
b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState) +34
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +70
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +139
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +59
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +44
System.Web.Mvc.Controller.<beginexecute>
b__15(IAsyncResult asyncResult, Controller controller) +39
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +62
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +139
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +59
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40
System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +39
System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +39
System.Web.Mvc.MvcHandler.<beginprocessrequest>
b__4(IAsyncResult asyncResult, ProcessRequestState innerState) +39
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +70
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +139
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +59
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +40
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +38
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9688704
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155
The behavior is normal as you can see from the following method (called when creating the user identity):
await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie)
in SignInAsync method.
In the implementation of CreateIdentityAsync:
...
ClaimsIdentity claimsIdentity = new ClaimsIdentity(authenticationType, this.UserNameClaimType, this.RoleClaimType);
claimsIdentity.AddClaim(new Claim(this.UserIdClaimType, user.Id, "http://www.w3.org/2001/XMLSchema#string"));
claimsIdentity.AddClaim(new Claim(this.UserNameClaimType, user.UserName, "http://www.w3.org/2001/XMLSchema#string"));
claimsIdentity.AddClaim(new Claim("http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider", "ASP.NET Identity", "http://www.w3.org/2001/XMLSchema#string"));
if (manager.SupportsUserRole)
{
foreach (string rolesAsync in await manager.GetRolesAsync(user.Id))
{
claimsIdentity.AddClaim(new Claim(this.RoleClaimType, rolesAsync, "http://www.w3.org/2001/XMLSchema#string"));
}
}
if (manager.SupportsUserClaim)
{
claimsIdentity.AddClaims(await manager.GetClaimsAsync(user.Id));
}
...
As you can see there are three claims added by default. To them are added your "custom" claims. This is why you'll have duplicated claims, meaning that SingleOrDefault call on the claims collection will throw the error that you've mentioned.
As a solution you can either use other claims either update them, after the identity creation, it's up to your business need.

System.Security.SecurityException: Security error while trying to consume WCF Data service in Silverlight 5 application

I am trying to consume a WCF data service in a Silverlight 5 application/.NET 4.0 application. I can see the data in the web browser as Atom feeds when i query the service manually.
However when i try to query the data via standard approaches i am getting the following error:
{System.Security.SecurityException: Security error.
at System.Net.Browser.ClientHttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
at System.Data.Services.Http.ClientHttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
at System.Data.Services.Client.QueryResult.AsyncEndGetResponse(IAsyncResult asyncResult)}
Inner exception is null. So no meaningfull information is available as yet.
My Code
public partial class ProjectWindow : ChildWindow
{
XYZEntitis.XYZEntitis db = new XYZEntitis.XYZEntitis(new Uri("http://google.com/wcfdataservice1.svc/"));
DataServiceCollection<XYZEntitis.Label> dscCats = new DataServiceCollection<XYZEntitis.Label>();
CollectionViewSource customerAddressViewSource;
ObservableCollection<XYZEntitis.Label> labelsBindingCollection = new ObservableCollection<XYZEntitis.Label>();
public ProjectWindow()
{
InitializeComponent();
btnBack.IsEnabled = false;
//Load Project categories
BindProjectCategories();
}
public void BindProjectCategories()
{
#region Code
//#############################################
//Approach # 01 : Raises Security Exception
//#############################################
//DataServiceQuery<XYZEntitis.Label> query = db.Labels;
//query.BeginExecute(
// s =>
// {
// var state = s.AsyncState as DataServiceQuery<XYZEntitis.Label>;
// var data = new ObservableCollection<XYZEntitis.Label>();
// foreach (var entity in state.EndExecute(s))
// data.Add(entity);
// cbCategoryName.ItemsSource = data;
// }, query);
#endregion
//#############################################
//Approach No # 2 : 0 Records are returned
//#############################################
var cats = from cat in db.Labels select cat;
//cats.ToList();
dscCats.LoadCompleted += this.dscCats_LoadCompleted;
dscCats.LoadAsync(cats);
//#############################################
//Approach # 3 : Security Exception
//#############################################
//var query = from cat in db.Labels select cat;
//((DataServiceQuery<XYZEntitis.Label>)query).BeginExecute(OnCategoriesFecthComplete, query);
}
private void OnCategoriesFecthComplete(IAsyncResult ar)
{
var query = ar.AsyncState as DataServiceQuery<XYZEntitis.Label>;
// Get the response of the query.
var response = query.EndExecute(ar);
foreach (XYZEntitis.Label label in response)
{
labelsBindingCollection.Add(label);
}
cbCategoryName.ItemsSource = labelsBindingCollection;
}
private void dscCats_LoadCompleted(object sender, LoadCompletedEventArgs e)
{
if (dscCats.Continuation != null)
{
dscCats.LoadNextPartialSetAsync();
}
else
{
cbCategoryName.ItemsSource = dscCats;
#region code
//var data = (DataServiceCollection<XYZEntitis.Label>)sender;
//cbCategoryName.ItemsSource = data;
//cbCategoryName.DisplayMemberPath = "Name";
//customerAddressViewSource =
// (CollectionViewSource)this.Resources["customerAddressViewSource"];
//customerAddressViewSource.Source = dscCats;
#endregion
}
}
}
Complete Stack Trace (Stack Trace 1):
System.InvalidOperationException was unhandled by user code
Message=An error occurred while processing this request.
StackTrace:
at System.Data.Services.Client.BaseAsyncResult.EndExecute[T](Object source, String method, IAsyncResult asyncResult)
at System.Data.Services.Client.QueryResult.EndExecute[TElement](Object source, IAsyncResult asyncResult)
at System.Data.Services.Client.DataServiceRequest.EndExecute[TElement](Object source, DataServiceContext context, IAsyncResult asyncResult)
at System.Data.Services.Client.DataServiceQuery`1.EndExecute(IAsyncResult asyncResult)
at ThreatModeler.Silverlight.ProjectWindow.OnCategoriesFecthComplete(IAsyncResult ar)
at System.Data.Services.Client.BaseAsyncResult.HandleCompleted()
at System.Data.Services.Client.QueryResult.AsyncEndGetResponse(IAsyncResult asyncResult)
at System.Data.Services.Client.BaseAsyncResult.<>c_DisplayClass1.b_0(IAsyncResult asyncResult)
at System.Net.Browser.ClientHttpWebRequest.<>c_DisplayClass1a.b_18(Object state2)
at System.Threading.QueueUserWorkItemCallback.WaitCallback_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem()
at System.Threading.ThreadPoolWorkQueue.Dispatch()
at System.Threading._ThreadPoolWaitCallback.PerformWaitCallback()
InnerException: System.Security.SecurityException
Message=Security error.
StackTrace:
at System.Net.Browser.ClientHttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
at System.Data.Services.Http.ClientHttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
at System.Data.Services.Client.QueryResult.AsyncEndGetResponse(IAsyncResult asyncResult)
InnerException:
Complete Stack Trace (Stack Trace #02)
{System.InvalidOperationException: An error occurred while processing
this request. ---> System.Security.SecurityException: Security error.
at System.Net.Browser.ClientHttpWebRequest.EndGetResponse(IAsyncResult
asyncResult) at
System.Data.Services.Http.ClientHttpWebRequest.EndGetResponse(IAsyncResult
asyncResult) at
System.Data.Services.Client.QueryResult.AsyncEndGetResponse(IAsyncResult
asyncResult) --- End of inner exception stack trace --- at
System.Data.Services.Client.BaseAsyncResult.EndExecute[T](Object
source, String method, IAsyncResult asyncResult) at
System.Data.Services.Client.QueryResult.EndExecute[TElement](Object
source, IAsyncResult asyncResult) at
System.Data.Services.Client.DataServiceRequest.EndExecute[TElement](Object
source, DataServiceContext context, IAsyncResult asyncResult) at
System.Data.Services.Client.DataServiceQuery`1.EndExecute(IAsyncResult
asyncResult) at
ThreatModeler.Silverlight.ProjectWindow.b_0(IAsyncResult
s) at System.Data.Services.Client.BaseAsyncResult.HandleCompleted()
at
System.Data.Services.Client.QueryResult.AsyncEndGetResponse(IAsyncResult
asyncResult) at
System.Data.Services.Client.BaseAsyncResult.<>c_DisplayClass1.b_0(IAsyncResult
asyncResult) at
System.Net.Browser.ClientHttpWebRequest.<>c_DisplayClass1a.b__18(Object
state2) at
System.Threading.QueueUserWorkItemCallback.WaitCallback_Context(Object
state) at System.Threading.ExecutionContext.Run(ExecutionContext
executionContext, ContextCallback callback, Object state, Boolean
preserveSyncCtx) at
System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem()
at System.Threading.ThreadPoolWorkQueue.Dispatch() at
System.Threading._ThreadPoolWaitCallback.PerformWaitCallback()}
This worked for me. In my service
Select Data under Installed Templates, and choose XML File. Name the file clientaccesspolicy.xml.
Enter the following contents for the file:
<?xml version="1.0" encoding="utf-8"?>
<access-policy>
<cross-domain-access>
<policy>
<allow-from http-request-headers="*">
<domain uri="http://*" />
<domain uri="https://*" />
</allow-from>
<grant-to>
<resource path="/" include-subpaths="true"/>
</grant-to>
</policy>
</cross-domain-access>
</access-policy>

Unable to use PostFile to upload image

I am trying to use PostFile to upload an image. As a simple example I have the following DTO:
[Route("/Pictures/{Id}", "GET, PUT, DELETE")]
public class Picture
{
public int Id { get; set; }
}
public class PictureResponse : IHasResponseStatus
{
public int Id { get; set; }
#region Implementation of IHasResponseStatus
public ResponseStatus ResponseStatus { get; set; }
#endregion
}
My GET works fine:
public override object OnGet(Picture request)
{
var memoryStream = new MemoryStream();
PictureRepository.Get(request.Id).Save(memoryStream, ImageFormat.Png);
return new HttpResult(memoryStream, "image/png");
}
But my PostFile blows up:
var imagePathInfo = new FileInfo(#"C:\Users\Mark\Downloads\avatars\symang.jpg");
var serviceClient = new JsonServiceClient("http://localhost:52712/api")
serviceClient.PostFile<PictureResponse>("/Pictures/{0}".Fmt(id), imagePathInfo, MimeTypes.GetMimeType(imagePathInfo.Name));
Here's the error and stack trace:
Server Error in '/' Application.
An existing connection was forcibly closed by the remote host
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Net.Sockets.SocketException: An existing connection was forcibly closed by the remote host
Source Error:
Line 32: var imagePathInfo = new FileInfo(#"C:\Users\Mark\Downloads\avatars\symang.jpg");
Line 33: var serviceClient = new JsonServiceClient("http://localhost:52712/api");
Line 34: serviceClient.PostFile<PictureResponse>("/Pictures/{0}".Fmt(id), imagePathInfo, MimeTypes.GetMimeType(imagePathInfo.Name));
Line 35: RedirectToAction("Index");
Line 36: return View();
Source File: C:\Users\Mark\Documents\Visual Studio 2010\Projects\Sandbox\UploadFileAttachments\UploadFileAttachments\Controllers\HomeController.cs Line: 34
Stack Trace:
[SocketException (0x2746): An existing connection was forcibly closed by the remote host]
System.Net.Sockets.Socket.Receive(Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags) +6210712
System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size) +134
[IOException: Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.]
System.Net.ConnectStream.Read(Byte[] buffer, Int32 offset, Int32 size) +318
System.Net.HttpWebRequest.MakeMemoryStream(Stream stream) +221
[WebException: The underlying connection was closed: An unexpected error occurred on a receive.]
System.Net.HttpWebRequest.GetResponse() +6115603
ServiceStack.ServiceClient.Web.ServiceClientBase.PostFile(String relativeOrAbsoluteUrl, Stream fileToUpload, String fileName, String mimeType) in C:\src\ServiceStack\src\ServiceStack.Common\ServiceClient.Web\ServiceClientBase.cs:815
ServiceStack.ServiceClient.Web.ServiceClientBase.PostFile(String relativeOrAbsoluteUrl, FileInfo fileToUpload, String mimeType) in C:\src\ServiceStack\src\ServiceStack.Common\ServiceClient.Web\ServiceClientBase.cs:790
UploadFileAttachments.Controllers.HomeController.ChangePicture(Int32 id) in C:\Users\Mark\Documents\Visual Studio 2010\Projects\Sandbox\UploadFileAttachments\UploadFileAttachments\Controllers\HomeController.cs:34
lambda_method(Closure , ControllerBase , Object[] ) +150
System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +17
System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +208
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +27
System.Web.Mvc.<>c__DisplayClass15.<InvokeActionMethodWithFilters>b__12() +55
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation) +263
System.Web.Mvc.<>c__DisplayClass17.<InvokeActionMethodWithFilters>b__14() +19
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodWithFilters(ControllerContext controllerContext, IList`1 filters, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +191
System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +343
System.Web.Mvc.Controller.ExecuteCore() +116
System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +97
System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext) +10
System.Web.Mvc.<>c__DisplayClassb.<BeginProcessRequest>b__5() +37
System.Web.Mvc.Async.<>c__DisplayClass1.<MakeVoidDelegate>b__0() +21
System.Web.Mvc.Async.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _) +12
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62
System.Web.Mvc.<>c__DisplayClasse.<EndProcessRequest>b__d() +50
System.Web.Mvc.SecurityUtil.<GetCallInAppTrustThunk>b__0(Action f) +7
System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Action action) +22
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +60
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +8970061
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +184
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.272
I'm sure I must be misunderstanding how to use PostFile. By the way, I never hit my OnPost method on my service. Thanks for any insights.
PostFile does a HTTP POST.
But your service only allows GET, PUT and DELETE because of your route in the first line of your example code:
[Route("/Pictures/{Id}", "GET, PUT, DELETE")]
Solution:
Either include POST in your route:
[Route("/Pictures/{Id}", "GET, PUT, DELETE, POST")]
...or just omit the HTTP verbs:
[Route("/Pictures/{Id}")]

Resources