Nancy Self-Host 404 Errors - nancy

I'm trying to build a simple Nancy self host. I got it working if I send in the proper path, but if I send empty path after port #, I get is error 404. If I send an invalid path I get error 500. What I want is to have a catch-all Get which is used whenever a request is sent with an invalid path.
Here is my program.cs
using System.Diagnostics;
using Nancy;
using Nancy.Hosting.Self;
namespace NancyDataService
{
class Program
{
static void Main(string[] args)
{
var uri = new Uri("http://localhost:8080");
var hostConfig = new HostConfiguration();
hostConfig.UrlReservations.CreateAutomatically = true;
hostConfig.RewriteLocalhost = false;
using (var nancyHost = new NancyHost(uri, new DefaultNancyBootstrapper(), hostConfig))
{
nancyHost.Start();
Console.WriteLine("Nancy now listening on http://localhost:8080. Press enter to stop");
try
{
Process.Start("http://localhost:8080");
}
catch (Exception)
{
}
Console.ReadKey();
}
Console.WriteLine("Stopped. Good bye!");
}
}
}
Here is my main module:
using Nancy;
namespace NancyDataService
{
public class MainModule: NancyModule
{
public MainModule()
{
string json_error = #"{""status"":""fail"",""reason"":""{0}""}";
string json;
Get("test", parms =>
{
return "test";
});
// this is default if desired path not sent
Get("{parm1}", parms =>
{
json = string.Format(json_error, "Invalid method name supplied");
//return (Response)json;
return json;
});
}
}
}
I've changed the Get syntax to match the Nancy 2.0 way. I was expecting that the last Get in the above code would be processed, and give me a default error message. If I enter http://localhost:8080/ in browser, I get error 404 response. If I enter http://localhost:8080/test it works fine. If I enter http://localhost:8080/anythingElse I get Error 500, Internal Server Error.
What I would like is to have a "default" get section so any unexpected path entered (including no path at all) after port #, it would take that branch.
BTW, this is targeting .Net Core 3.0, which Nancy says may not work. The warning in my Nancy.Hosting.Self package has a warning which says it was restored using .Net Framework (4.6.1 - 4.8). Could that be the issue?
Any ideas how to make that work? Thanks...

Solved most issues. Need Get("/", ... for empty path, and Get("/{parm}",... for bad path. Seems string.Format causes error 500 but json_error.Replace("{0}", "new text") works fine. What's up with that?

Related

Unable to get IAM security credentials from EC2 Instance Metadata Service error when using Aws Sdk in UWP

I'm working with Aws Sdk and I'm trying to implement a login UI using UWP. I followed this online tutorial (which is for WPF) and I tried to make it works for the Universal Windows Platform as well.
The core part of the source code is the following (please note that is 90% similar to the one posted in the tutorial. The "only difference" is that I used
InitiateAuthAsync
instead of
AdminInitiateAuthAsync
<!-- language: lang-cs -->
private readonly AmazonCognitoIdentityProviderClient _client;
private readonly string _clientId = "32fsoifj93fjsiispat";
public MainPage()
{
this.InitializeComponent();
var amazonCognitoIdentityProviderConfig = new AmazonCognitoIdentityProviderConfig();
amazonCognitoIdentityProviderConfig.ServiceURL = "https://cognito-idp.eu-central-1.amazonaws.com/";
_client = new AmazonCognitoIdentityProviderClient(amazonCognitoIdentityProviderConfig);
}
private async Task<bool> CheckPasswordAsync(string userName, string password)
{
try
{
List<HttpHeader> httpHeaders = new List<HttpHeader>();
HttpHeader httpHeader = new HttpHeader
{
HeaderName = "X-Amz-Target",
HeaderValue = "AWSCognitoIdentityProviderService.InitiateAuth"
};
httpHeaders.Add(httpHeader);
httpHeader = new HttpHeader
{
HeaderName = "Content-Type",
HeaderValue = "application/x-amz-json-1.1"
};
httpHeaders.Add(httpHeader);
var authReq = new InitiateAuthRequest()
{
ClientId = _clientId,
AuthFlow = AuthFlowType.USER_PASSWORD_AUTH,
};
authReq.AuthParameters.Add("USERNAME", userName);
authReq.AuthParameters.Add("PASSWORD", password);
var authResp = await _client.InitiateAuthAsync(authReq);
return true;
}
catch (Exception ex)
{
return false;
}
}
Please consider that it is working properly with WPF framework. I'm able to get the TokenId and RefreshToken.
But if I try to copy and paste the same code in UWP I get the exception:
'Unable to get IAM security credentials from EC2 Instance Metadata Service.'
And if I try to investigate with Fiddler I get the following error:
[Fiddler] The connection to '169.254.169.254' failed. Error: NetworkUnreachable (0x2743). System.Net.Sockets.SocketException A socket operation was attempted to an unreachable network 169.254.169.254:80
I really can't understand why it tries to connect to the '169.254.169.254' address. Googling around I found other people experiencing the same issue (for example here). Do you have any idea?

Hystrix Javanica : Call always returning result from fallback method.(java web app without spring)

I am trying to integrate Hystrix javanica into my existing java EJB web application and facing 2 issues with running it.
When I try to invoke following service it always returns response from fallback method and I see that the Throwable object in fallback method has "com.netflix.hystrix.exception.HystrixTimeoutException" exception.
Each time this service is triggered, HystrixCommad and fallback methods are called multiple times around 50 times.
Can anyone suggest me with any inputs? Am I missing any configuration?
I am including following libraries in my project.
project libraries
I have setup my aspect file as follows:
<aspectj>
<weaver options="-verbose -showWeaveInfo"></weaver>
<aspects>
<aspect name="com.netflix.hystrix.contrib.javanica.aop.aspectj.HystrixCommandAspect"/>
</aspects>
</aspectj>
Here is my config.properties file in META-INF/config.properties
hystrix.command.default.execution.timeout.enabled=false
Here is my rest service file
#Path("/hystrix")
public class HystrixService {
#GET
#Path("clusterName")
#Produces({ MediaType.APPLICATION_JSON })
public Response getClusterName(#QueryParam("id") int id) {
ClusterCmdBean clusterCmdBean = new ClusterCmdBean();
String result = clusterCmdBean.getClusterNameForId(id);
return Response.ok(result).build();
}
}
Here is my bean class
public class ClusterCmdBean {
#HystrixCommand(groupKey = "ClusterCmdBeanGroup", commandKey = "getClusterNameForId", fallbackMethod = "defaultClusterName")
public String getClusterNameForId(int id) {
if (id > 0) {
return "cluster"+id;
} else {
throw new RuntimeException("command failed");
}
}
public String defaultClusterName(int id, Throwable e) {
return "No cluster - returned from fallback:" + e.getMessage();
}
}
Thanks for the help.
If you want to ensure you are setting the property, you can do that explicitly in the circuit annotation itself:
#HystrixCommand(commandProperties = {
#HystrixProperty(name = "execution.timeout.enabled", value = "false")
})
I would only recommend this for debugging purposes though.
Something that jumps out to me is that Javanica uses AspectJ AOP, which I have never seen work with new MyBean() before. I've always have to use #Autowired with Spring or similar to allow proxying. This could well just be something that is new to me though.
If you set a breakpoint inside the getClusterNameForId can you see in the stack trace that its being called via reflection (which it should be AFAIK)?
Note you can remove commandKey as this will default to the method name. Personally I would also remove groupKey and let it default to the class name.

Why is IE ignoring my attachment filename content-disposition?

I'm using ASP.NET Web API targeting the 4.5.2 framework and am trying to push out a CSV file generated by exporting data from a table. In Firefox and Chrome, everything works as expected, but with IE (I'm testing with 11), the filename is being ignored and IE is using the URL instead (with no extension). What am I doing wrong and how can I get around it?
Here's my controller method:
[HttpGet]
public HttpResponseMessage ExportToCSV([FromUri]DistributionSearchCriteria criteria)
{
// This creates the csv in the temp folder and returns the temp file name
var file = _repository.ExportToCSV(criteria);
// This FileHttpResponseMessage is a custom type which just deletes the temp file in dispose
var result = new FileHttpResponseMessage(file, HttpStatusCode.OK)
{
Content = new StreamContent(File.OpenRead(file))
};
result.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
{
FileName = "Distributions.csv"
};
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
return result;
}
Here's the custom FileHttpResponseMessage
public class FileHttpResponseMessage : HttpResponseMessage
{
private string _filePath;
public FileHttpResponseMessage(string filePath, HttpStatusCode statusCode) : base(statusCode)
{
_filePath = filePath;
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
if (disposing)
{
Content.Dispose();
if (File.Exists(_filePath))
{
try
{
System.Diagnostics.Debug.WriteLine("Deleting {0}", (object)_filePath);
File.Delete(_filePath);
System.Diagnostics.Debug.WriteLine("{0} deleted", (object)_filePath);
}
catch
{
System.Diagnostics.Debug.WriteLine("Error Deleting {0}", (object)_filePath);
}
}
}
}
}
and these are my two JavaScript methods in my AngularJS controller which launch the downloads:
vm.exportToCSV = function () {
var params = $httpParamSerializer(vm.searchCriteria);
$window.open(apiBase + 'Distribution/ExportToCSV?' + params, '_blank');
};
vm.exportAllToCSV = function () {
$window.open(apiBase + 'Distribution/ExportToCSV', '_blank');
};
From what I've read in other questions... setting the attachment; filename= should've been sufficient for IE. IE is prompting for a filename of "ExportToCSV".
I've also tried appending a bogus parameter like ?/distribution.csv and it changed the download filename but instead of distribution.csv it replaced the . with _ so the result was distribution_csv. Oh the pains of IE.
Update 1:
I've created a separate project to address only this issue and come up with specific workarounds. I've tried with and without quotes around the filename but I'm still no difference:
Update 2:
So I thought I would attempt to be "clever" and try to create a custom HTTP Handler for files with an extension:
Web.config
<!-- Route all files through asp -->
<modules runAllManagedModulesForAllRequests="true" />
<!-- Route all files through asp -->
<add name="FileDownloadHandler" path="/api/File/test.csv" verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0"/>
WebApiConfig.cs
config.Routes.MapHttpRoute(
name:"download",
routeTemplate: "api/File/test.csv",
defaults: new { controller = "File", action = "Get" }
);
as expected it used the test.csv but it replaced the . with _ resulting in a test_csv extensionless download.
This is the weirdest bug I've ever ran into. I'm not sure whether to attribute it to my anitvirus or not, but my CPU recently maxed out at 100% as a result of McAFEE going bananas and bringing my system to a crawl. As a result, I rebooted my machine. Now Internet Explorer is working as expected! I never would've guessed... I was beginning to question everything I thought I knew...
Moral of the story:

NotSupportedException in HttpWebRequest on Windows Phone 7

I have a Windows Phone 7 application built with silverlight. This application has been deployed. I've noticed in the log files that occasionally, my user's actions throw a "NotSupportedException". I have not been able to produce this. However, because of my logs, I know that it is happening in the Execute method shown here:
public void Execute()
{
try
{
// 1. Build the query
string serviceUrl = GetServiceUrl;
// 2. Asynchronously execute the query using HttpWebRequest
WebRequest request = HttpWebRequest.Create(serviceUrl);
request.BeginGetResponse(new AsyncCallback(ServiceRequest_Completed), request);
} catch (Exception ex)
{
LogException(ex, "1");
}
}
private void ServiceRequest_Completed(IAsyncResult result)
{
try
{
// 1. Get the response from the service call
WebRequest request = (WebRequest)(result.AsyncState);
WebResponse response = request.EndGetResponse(result);
// 2. Do stuff with response
}
catch (Exception ex)
{
LogException(ex, "2");
}
}
I know it is happening in the Execute method because the "1" is written in the log file instead of the "2" My question is, what would cause this? I looked at the MSDN documentation and it looks like I'm doing what I should be doing. Like I said, I can't reproduce it locally. But I do know that it is happening regularly by different users because of the log files.
There is a previous question with a very similar title - https://stackoverflow.com/questions/4053197/httpwebrequest-leads-me-to-system-notsupportedexception
The answer to that problem seems to have been using ServiceRequest_Completed instead of new AsyncCallback(ServiceRequest_Completed)

Silverlight communication with XML RPC console server

I want to comunicate with Console XML RPC server from my silvelight application. Is it possibile?
Steps:
1. Start the Console XML RPC server
Code for Console XML RPC server is this:
using System;
using System.Collections;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Http;
using CookComputing.XmlRpc;
public class StateNameServer : MarshalByRefObject, IStateName
{
public string GetStateName(int stateNumber)
{
return "whatever";
}
}
class _
{
static void Main(string[] args)
{
IDictionary props = new Hashtable();
props["name"] = "MyHttpChannel";
props["port"] = 5678;
HttpChannel channel = new HttpChannel(props,null,new XmlRpcServerFormatterSinkProvider());
ChannelServices.RegisterChannel(channel,false);
RemotingConfiguration.RegisterWellKnownServiceType(
typeof(StateNameServer),"statename.rem",WellKnownObjectMode.Singleton);
Console.WriteLine("Press <ENTER> to shutdown");
Console.ReadLine();
}
}
Run Silverlight application
I used the code from http://code.google.com/p/xmlrpc-silverlight/
I created new Silverlight application to which I have attached the code from that link. When I start web site (in localhost with port 1139) which executes my SL app happens SecurityException.
void ResponseResponse(IAsyncResult result)
{
XmlRpcHelperRequestState state = result.AsyncState as XmlRpcHelperRequestState;
try
{
state.Response = (HttpWebResponse)state.Request.EndGetResponse(result);
...
}
catch (Exception e)
{
// comes here with SecurityException
}
finally
{
...
}
}
I am using VS2008 Professional,XP Professional, .net 3.5, Silverlight3. I will gladly provide any additional information (or code) which is needed.
I suspect that this is a case of a missing clientaccesspolicy.xml file.
Since your silverlight app will have been launched from another authority it will attempt to access this file the http://localhost:5678/. Since you little test doesn't support that file Silverlight blocks this cross "domain" activity.

Resources