【问题标题】:Web api always return the server responded with a status of 405Web api 总是返回服务器响应状态为 405
【发布时间】:2015-04-28 20:06:36
【问题描述】:

使用 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"

然后我为 serveroauthoptions 实现了 Provider,如下所示。

 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 方法”。

其实我不知道我犯了什么错误。谁能告诉我解决方法?

我需要为此提供更多信息吗?

【问题讨论】:

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


    【解决方案1】:

    我想我已经在某个地方看到了这个问题的答案,但是找不到,所以这里是(在 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);
        }
    

    【讨论】:

    • 谢谢@steen。我已经按照你的建议实施了。但现在我收到类似“此请求的授权已被拒绝”之类的错误。
    • 注意,我没有为“/api/Common/LogIn”登录操作​​包含 [Authorize] 属性...
    • 非常感谢大家.. 但我发现了这个错误。我需要在方法之前包含 [AllowAnonymous] 标记。我认为默认情况下它会接受该方法。
    • @Jeeva,默认情况下它应该在没有 AllowAnonymous 的情况下工作,除非你有一个“filters.Add(new AuthorizeAttribute());”在从 Global.asax 调用的 FilterConfig 的 RegisterGlobalFilters 方法中注册(这不是一个坏主意)。
    • 非常感谢@ColeChamberlain
    猜你喜欢
    • 2021-12-28
    • 2021-12-18
    • 1970-01-01
    • 2014-08-09
    • 2020-06-03
    • 2021-08-26
    • 2018-12-16
    • 2018-06-18
    相关资源
    最近更新 更多