ASP.NET Web API Startup没有执行

本文介绍了在webapi项目中基于Microsoft.Owin.Security.OAuth实现Token发放过程,包括配置OAuthAuthorizationServerOptions,自定义OAuth授权提供者SimpleAuthorizationServerProvider,以及处理客户端验证和资源所有者凭据授予。当遇到404错误时,通过添加Microsoft.Owin.Host.SystemWeb引用成功解决了问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

webapi项目 基于Microsoft.Owin.Security.OAuth 实现发放Token

using API.BLL;
using API.Uti;
using Microsoft.Owin;
using Microsoft.Owin.Security.OAuth;
using Owin;
using System;
using System.Collections.Generic;
using System.Security.Claims;
using System.Threading.Tasks;
using System.Web.Http;
[assembly: OwinStartup(typeof(API.Startup))]

namespace API
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            // 有关如何配置应用程序的详细信息,请访问 https://go.microsoft.com/fwlink/?LinkID=316888
            try
            {
                HttpConfiguration config = new HttpConfiguration();
                ConfigureOAuth(app);

                WebApiConfig.Register(config);
                app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
                app.UseWebApi(config);
            }
            catch (Exception e)
            {
                Log4Helper.Error(e);
            }

        }

        public void ConfigureOAuth(IAppBuilder app)
        {
            try
            {
                OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
                {
                    AllowInsecureHttp = true,
                    TokenEndpointPath = new PathString("/api/token"),
                    AccessTokenExpireTimeSpan = TimeSpan.FromHours(8),
                    //AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(5),
                    Provider = new SimpleAuthorizationServerProvider()
                };
                app.UseOAuthAuthorizationServer(OAuthServerOptions);
                app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
            }
            catch (Exception e)
            {
                Log4Helper.Error(e);
            }
        }
    }

    /// <summary>
    /// Token验证
    /// </summary>
    public class SimpleAuthorizationServerProvider : OAuthAuthorizationServerProvider
    {
        Dictionary<string, string> dirusers = new Dictionary<string, string> {
            {"jnlocalserver","123456"}
        };

        public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
            await Task.Factory.StartNew(() => context.Validated());
        }

        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            await Task.Factory.StartNew(() => context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" }));

            //判断键存在
            if (dirusers.ContainsKey(context.UserName)) // True 
            {
                string val = dirusers[context.UserName];
                if (val != context.Password)
                {
                    context.SetError("invalid_grant", "The user name or password is incorrect.");
                    return;
                }
            }
            else
            {
                UserBLL userBLL = new UserBLL();
                if (userBLL.Verify(context.UserName, context.Password) == false)
                {
                    context.SetError("invalid_grant", "The user name or password is incorrect.");
                    return;
                }
            }

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

测试发现指定的路径不能访问,
在这里插入图片描述
访问结果提示404

<!DOCTYPE html>
<html>
<body bgcolor="white">
	<span><H1>“/”应用程序中的服务器错误。<hr width=100% size=1 color=silver></H1>
            <h2> <i>无法找到资源。</i> </h2></span>
	<font face="Arial, Helvetica, Geneva, SunSans-Regular, sans-serif ">
		<b> 说明: </b>HTTP 404。您正在查找的资源(或者它的一个依赖项)可能已被移除,或其名称已更改,或暂时不可用。请检查以下 URL 并确保其拼写正确。
		<br><br>
		<b> 请求的 URL: </b>/api/token<br><br>
		<hr width=100% size=1 color=silver>
		<b>版本信息:</b>&nbsp;Microsoft .NET Framework 版本:4.0.30319; ASP.NET 版本:4.8.4330.0
	</font>
</body>
</html>
<!-- 
[HttpException]: 未找到路径“/api/token”的控制器或该控制器未实现 IController。
   在 System.Web.Mvc.DefaultControllerFactory.GetControllerInstance(RequestContext requestContext, Type controllerType)
   在 System.Web.Mvc.DefaultControllerFactory.CreateController(RequestContext requestContext, String controllerName)
   在 System.Web.Mvc.MvcHandler.ProcessRequestInit(HttpContextBase httpContext, IController& controller, IControllerFactory& factory)
   在 System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state)
   在 System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state)
   在 System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData)
   在 System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
   在 System.Web.HttpApplication.ExecuteStepImpl(IExecutionStep step)
   在 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
-->

解决办法是添加引用Microsoft.Owin.Host.SystemWeb
在这里插入图片描述

测试成功
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值