可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
I am setting up a WebAPI endpoint for my API, but am having trouble getting my AngularJS calls to my PostRegister method to work.
The webAPI and Angular are on separate sites.
On the Startup.cs I have:
public void Configuration(IAppBuilder app)
{
ConfigureOAuth(app);
var config = new HttpConfiguration();
WebApiConfig.Register(config);
app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
app.UseWebApi(config);
}
private void ConfigureOAuth(IAppBuilder app)
{
var oAuthServerOptions = new OAuthAuthorizationServerOptions
{
AllowInsecureHttp = true,
TokenEndpointPath = new PathString(Paths.TokenPath),
AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(30),
Provider = Kernel.Get<IOAuthAuthorizationServerProvider>()
};
app.UseOAuthAuthorizationServer(oAuthServerOptions);
OAuthBearerOptions = new OAuthBearerAuthenticationOptions();
app.UseOAuthBearerAuthentication(OAuthBearerOptions);
}
Then on the controller, I have my method that is set to allow anonymous:
[AllowAnonymous]
public bool PostRegister(UserSignupForm form)
{
...
}
I've also updated the web.config:
<system.webServer>
<handlers>
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<remove name="OPTIONSVerbHandler" />
<remove name="TRACEVerbHandler" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
</system.webServer>
On the Angular side, I make a simple $http.post call:
saveRegistration: function (registration) {
return $http.post(baseUrl + '/api/signup/register', registration).then(function (response) {
return response;
});
}
When making the call using Postman, I get a successful response, but when doing the same call from Angular, I get the 405 error.
BitOfTech sample site, is sending the same request headers, but is able to get the Access-Control-Allow-XXX headers
I've updated my code to follow Token Based Authentication using ASP.NET Web API 2, Owin, and Identity
回答1:
I had similar issue recently. I added controller handler for the pre-flight OPTIONS
request and it solved the problem.
[AllowAnonymous]
[Route("Register")]
[AcceptVerbs("OPTIONS")]
public async Task<IHttpActionResult> Register()
{
return Ok();
}
回答2:
You might need to allow cors in your application for response headers. Below is sample for what I do in node.
res.header('Access-Control-Allow-Origin', '*');
res.header("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT, OPTIONS");
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
This could help you. Thanks.
回答3:
The problem is not with the angular. Though you get a response in Postman, its not problem in angular that request is not giving you the response. Problem is by default Postman does not post the Origin attribute
, which is needed to test CORS. Chrome does block the Origin attribute by default, hence the request is not treated as if its coming from a different domain.
So how to test CORS in Postman
you would need a different chrome extension with same name POSTMAN - Rest Client (Packaged App), and use its 'Request Interceptor toggle switch' to enable it to send the ORIGIN attribute.
read here, section restricted header
below is the sample screen shot when you dont send the ORIGIN attributes
and the same request;s response in POSTMAN when you send the ORIGIN attribute
so if you see, when you add origin, that only when you get the ACCESS-CONTROL-* attributes in response.
I hope this also answer your query about
BitOfTech sample site, is sending the same request headers, but is
able to get the Access-Control-Allow-XXX headers"
Web Api Part
Coming back to your case, you do not have CORS enabled in web-api. First enable CORS in web-api. To enable CORS globally use
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
var cors = new EnableCorsAttribute("www.example.com", "*", "*");
config.EnableCors(cors);
// ...
}
}
-- you can find lot of resources around net on how to add it on controller level etc.
Angular Part
you first need to make sure that the CORS is working in POSTMAN and then try to access that url in angular.
to enable cors in angular you need below code in your app.config() function.
myApp.config(function($httpProvider) {
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];
});
Note : For the Experts
Origin attributes is needed to test CORS.
I am not very sure on this part, but seems like the case as per the response I see in Postman. It would be great if anyone can shed light on the role Origin attribute
in Cors.
回答4:
This sounds like a cross-origin issue. You should install Fiddler and check if the 405 response is caused by the pre-flight request (OPTIONS verb) that is issued by the browser when you're calling a resource on a different origin.
See this article for a nice explanation of CORS: http://www.html5rocks.com/en/tutorials/cors/
回答5:
I believe you are missing annotation on your API Controller, you should add annotation on APIController as
[RoutePrefix("api/signup")]
Otherwise your WebApiConfig
should be have route define like Below
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
And to setup CORS you always need to send your credential on every single call to server.
Then there is easy way to do this in angular by setting $http provider default option.
You can do this at config phase of angular.
CODE
angular.module('myApp',[])
.config([
'$httpProvider',
function($httpProvider) {
$httpProvider.defaults.withCredentials = true;
}
]);
Above setting will add credential in each $http call.
Also refer this post. Some what the same problem.
This may help to solve your problem.
Thanks.