Web api始终返回服务器响应状态为405

时间:2015-02-26 12:32:59

标签: angularjs asp.net-web-api asp.net-identity asp.net-web-api2 asp.net-identity-2

使用Angularjs开发了一个项目,web api并实现了自定义存储标识。

在实现asp.net身份之前,调用方法运行良好。

在实现身份后,当我使用angularjs调用post方法时,web api总是返回,“服务器响应状态为405”。

我不知道原因。在这里,我逐步介绍了如何实现web api。

OAuthBearerOptions = new OAuthBearerAuthenticationOptions();

            OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
            {

                AllowInsecureHttp = true,
                TokenEndpointPath = new PathString("/token"),
                AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(30)
                //,
                //Provider = new SimpleAuthorizationServerProvider()
                //RefreshTokenProvider = new SimpleRefreshTokenProvider()
            };


            // Token Generation
            app.UseOAuthAuthorizationServer(OAuthServerOptions);
            app.UseOAuthBearerAuthentication(OAuthBearerOptions);
app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath = new PathString("/api/Common/LogIn"),
                Provider = new CookieAuthenticationProvider
                {   //error on the line below
                    OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser, Guid>(
                            TimeSpan.FromMinutes(20),
                            (manager, user) => user.GenerateUserIdentityAsync(manager),
                            (identity) => Guid.Parse(identity.GetUserId()))
                }
            });

当我打电话给像

这样的彻底的angluarjs时
$http.post('/api/Common/LogIn', loginData).success(function (response) {

            localStorageService.set('authorizationData',
            { token: response.access_token, userName: response.userName });

            _authentication.isAuth = true;
            _authentication.userName = response.userName;

            deferred.resolve(response);

        }).error(function (err, status) {
            _logOut();
            deferred.reject(err);
        });

Web api实际上重定向到"http://localhost:4082/api/Common/LogIn?ReturnUrl=%2Fapi%2FCommon%2FLogIn"

然后我实现了像服务器一样的提供者,如下所示。

 public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
    {
        context.Validated();
    }

    public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
    {

        context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
        ApplicationUserManager UserManager = HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>();
        var user = await UserManager.FindByNameAsync(context.UserName);
        PasswordVerificationResult result = PasswordVerificationResult.Failed;

        if (user == null)
        {
            context.SetError("invalid_grant", "The user name or password is incorrect.");
            return;
        }
        else
        {
            result = UserManager.PasswordHasher.VerifyHashedPassword(user.Password, context.Password);

            if (!(result == PasswordVerificationResult.Success))
            {
                context.SetError("invalid_grant", "The user name or password is incorrect.");
            }
        }

        var identity = new ClaimsIdentity(context.Options.AuthenticationType);
        identity.AddClaim(new Claim("sub", context.UserName));
        context.Validated(identity);
    }

在实现提供者之后,当我通过angularjs调用sigin post方法时,我总是得到“未经授权的错误”,或者有时我通过链接"http://localhost:4082/api/Common/LogIn?ReturnUrl=%2Fapi%2FCommon%2FLogIn"得到“调用方法不支持get方法”。

其实我不知道我做错了什么。有人可以告诉我解决方案吗?

我是否需要向此提供更多信息?

1 个答案:

答案 0 :(得分:0)

我想我已经在某个地方找到了这个问题的答案,但找不到它,所以这里(在App_Start的Startup.Auth.cs文件中):

    public void ConfigureAuthentication(IAppBuilder app) {
        app.UseCookieAuthentication(new CookieAuthenticationOptions {
            AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
            LoginPath = new PathString("/Login"),
            Provider = new CookieAuthenticationProvider {
                OnApplyRedirect = ctx => {
                    if (!IsApiRequest(ctx.Request)) {
                        ctx.Response.Redirect(ctx.RedirectUri);
                    }
                }
            }
        });
    }

    private static Boolean IsApiRequest(IOwinRequest request) {
        String apiPath = VirtualPathUtility.ToAbsolute("~/api/");
        return request.Uri.LocalPath.StartsWith(apiPath);
    }