【问题标题】:ASP.NET Web API 2 Url-based VersioningASP.NET Web API 2 基于 URL 的版本控制
【发布时间】:2016-07-17 20:27:48
【问题描述】:

我一直在尝试在 Web API 2.0 中配置基于 Url 的版本控制,但到目前为止它不起作用。

WebApiConfig

// Web API configuration and services
// Configure Web API to use only bearer token authentication.
config.SuppressDefaultHostAuthentication();
config.Filters.Add(new ostAuthenticationFilter(OAuthDefaults.AuthenticationType));

// Web API routes
config.MapHttpAttributeRoutes();

config.Routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{id}",
    defaults: new { id = RouteParameter.Optional }
);

控制器

/// <summary>
/// 
/// </summary>
[RoutePrefix("api/v1/customers")]
[ValidateRequestModel]
public class CustomersController : ApiController
{
  ....
} 

没有 v1 也可以正常工作,但是当我将 v1 添加到上述路由前缀时,IIS 给了我 403 禁止错误(IIS 7.5 详细错误 - 403.18 - 禁止)。您能帮忙提出问题所在吗?

更新:

/// <summary>
    /// 
    /// </summary>
    /// <param name="request"></param>
    /// <returns></returns>
    [Route("")]
    [HttpPost]
    [ResponseType(typeof(CustomerCreateResponseMessage))]
    public HttpResponseMessage CreateFolder([FromBody] CustomerCreateRequestMessage request)
    {
        return Request.CreateResponse<CustomerCreateResponseMessage>(HttpStatusCode.Created, new CustomerCreateResponseMessage { Message = "OK!"  });
    }

谢谢

【问题讨论】:

  • 显示您调用的提供 403 状态代码的操作和网址
  • 乍一看,HostAuthenticationFilter 似乎是原因,但如果没有问题中的更多细节,就无法确定
  • @Nkosi ...我刚刚添加了屏幕截图。
  • 您没有包含应该调用的操作的代码。
  • 好吧,鉴于我没有足够的关于被调用动作的信息,这是我在黑暗中拍摄的。将 [AllowAnonymous] 属性放在您尝试执行的操作上。鉴于路径与路由前缀匹配,我猜它是根操作,这将是您具有 [Route("")] 属性的操作。

标签: asp.net iis asp.net-web-api asp.net-mvc-5 asp.net-web-api2


【解决方案1】:

您的配置中的HostAuthenticationFilter 表示请求需要经过身份验证/授权才能访问您的Web api。

或者注释掉过滤器,这样你就可以在邮递员中测试它而无需验证请求

//config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));

允许控制器通过在操作上使用[AllowAnonymous] 属性来处理匿名请求。

[RoutePrefix("api/v1/customers")]
[ValidateRequestModel]
public class CustomersController : ApiController
{        
    [AllowAnonymous] // <--This will allow you to test unauthenticated requests
    [Route("")]
    [HttpPost]
    [ResponseType(typeof(CustomerCreateResponseMessage))]
    public HttpResponseMessage CreateFolder([FromBody] CustomerCreateRequestMessage request) {...}
} 

【讨论】:

  • 让我试试看。
  • 你在哪里托管 web api,或者只是在 Visual Studio 中运行它?
  • Windows 7 Professional 上的 IIS 7.5。
  • 查看您的 web.config 文件,看看您是否正确配置了它
  • 你说它可以在没有路由前缀的情况下工作。它与什么网址一起使用
【解决方案2】:

您所看到的 (403.18) 它只是对真正错误的掩饰,它的发生是因为 IIS 尝试加载不在您当前应用程序池范围内的资源(可能是自定义错误页面?) projectabc”,但在其他地方。它在错误页面的请求 URL 属性中明确标记:http://localhost:80/api.php?name=folders(这绝对不是 Web api 的东西!)。

修复此错误,查看真正的错误页面,并可能获取更多详细信息(问题可能是您没有向 API 发送正确的身份验证标头,正如 @Nkosi 指出的那样)。

查看此link,了解类似情况下 403.18 错误的具体描述。

【讨论】:

  • 我看到了 PHP 路径,但认为这与邮递员有关,因为我没有使用该工具的经验。
猜你喜欢
  • 2018-02-21
  • 1970-01-01
  • 2020-10-03
  • 1970-01-01
  • 2017-03-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-31
相关资源
最近更新 更多