Donny V.
Donny V.

Reputation: 23556

How to add a request header in Nancyfx?

I tried adding this in the bootstrapper in the ApplicationStartup override.

pipelines.AfterRequest.AddItemToStartOfPipeline(ctx =>
{
  ctx.Request.Headers["x-fcr-version"] = "1";
});

Its giving me errors.

Can anyone point me in the right direction?

Upvotes: 4

Views: 5098

Answers (3)

Alexandr
Alexandr

Reputation: 695

For some reason the answer with content negotiation is not working in my case but I found another way:

Get["result"] = x=>
{
    ...

    var response = Response.AsText(myModel, "application/json");
    response.Headers.Add("Access-Control-Allow-Origin", "http://example.com");
    response.Headers.Add("Access-Control-Allow-Credentials", "true");

    return response;
  };

Upvotes: 0

Dai Bok
Dai Bok

Reputation: 3616

Since this question is about adding headers to a nancy request, which I need to do as I need to add an origin header, and some others when making requests to my app api.

In order to get it to work, I did the following:

    //create headers dictionary
    var myHeaders = new Dictionary<string, IEnumerable<string>>();
    myHeaders.Add("origin",new List<String>{"https://my.app.com"});
    //..... snip - adding other headers ....//  

    var uri = new Uri("https://my.api.com");
    var request = new Nancy.Request("OPTIONS", uri, null, myHeaders,"127.0.0.1", null);

I found reading the nancy request source source useful, as the null parameters, (body and protocolVersion) and I passed through get initialized if not set.

Upvotes: 0

Pure.Krome
Pure.Krome

Reputation: 86967

Notice how you are trying to set the Request while trying to manipulate the Response ?

Try this..

protected override void RequestStartup(TinyIoCContainer container, IPipelines pipelines, NancyContext context)
{
    base.RequestStartup(container, pipelines, context);

    pipelines.AfterRequest.AddItemToEndOfPipeline(c =>
    {
        c.Response.Headers["x-fcr-version"] = "1";
    });
}

This is what my Response looks like..

enter image description here

Or .. you can use Connection Negotiation if you're going to set it at the module level...

Get["/"] = parameters => {
    return Negotiate
        .WithModel(new RatPack {FirstName = "Nancy "})
        .WithMediaRangeModel("text/html", new RatPack {FirstName = "Nancy fancy pants"})
        .WithView("negotiatedview")
        .WithHeader("X-Custom", "SomeValue");
};

Upvotes: 9

Related Questions