问题
I want to accept options requests from an angular website. Every endpoint (signup, login etc) needs to accept the options http verb.
I will then add the following to the response header.
After += ctx =>
{
ctx.Response.WithHeader("Access-Control-Allow-Origin", "*");
ctx.Response.WithHeader("Access-Control-Allow-Headers", "accept, client-token, content-type");
ctx.Response.WithHeader("Access-Control-Allow-Methods", "POST, GET");
ctx.Response.WithHeader("Access-Control-Max-Age", "30758400");
};
What i dont want to do is add an extra route for every endpoint like
Post[path + "Login"] = x => Login();
Options[path + "Login"] = x => Login();
This would be masses of boilerplate code.
Is there a way i can intercept any options request using a wildcard route so that all my endpoints can accept options requests?
回答1:
Nancy has implicit routes for OPTIONS
requests, i.e. a user defined OPTIONS
route has not been defined. See OptionsRoute for reference.
If you want custom behavior for OPTIONS
requests, you could alternatively add a AfterRequest
hook:
protected override void ApplicationStartup(TinyIoCContainer container, IPipelines pipelines)
{
pipelines.AfterRequest += ctx =>
{
// This will always be called at the end of the request
if (ctx.Request.Method.Equals("OPTIONS", StringComparison.Ordinal))
{
ctx.Response.WithHeader("Access-Control-Allow-Origin", "*");
ctx.Response.WithHeader("Access-Control-Allow-Headers", "accept, client-token, content-type");
ctx.Response.WithHeader("Access-Control-Allow-Methods", "POST, GET");
ctx.Response.WithHeader("Access-Control-Max-Age", "30758400");
}
}
}
But I'm not really sure why you would only add CORS headers to OPTIONS
responses?
回答2:
so if you need all the headers as i did you can add them the ApplicationStartupmethod in the nancy bootstraper as below. The default nancy behavior will be like a wildcard route on any options request and add these headers to the response.
protected override void ApplicationStartup(TinyIoCContainer container, IPipelines pipelines)
{
pipelines.AfterRequest += ctx =>
{
ctx.Response.WithHeader("Access-Control-Allow-Origin", "*");
ctx.Response.WithHeader("Access-Control-Allow-Headers", "accept, client-token, content-type");
ctx.Response.WithHeader("Access-Control-Allow-Methods", "POST, GET");
ctx.Response.WithHeader("Access-Control-Max-Age", "30758400");
};
}
来源:https://stackoverflow.com/questions/22068456/implementing-options-httpverb