【问题标题】:WebAPI controller not working while another one doesWebAPI 控制器不工作,而另一个控制器工作
【发布时间】:2020-08-26 07:40:08
【问题描述】:

我有一个在本地运行良好的 API,但当我将它移到实时环境时却不行。

受影响控制器上的主要 POST 操作返回:

NotFound

通过测试 GET 操作我回来了:

"Message": "No HTTP resource was found that matches the request URI

奇怪的是,当我上传了一个与主控制器中使用的测试操作相同的 testController 时,我从 API 得到了正确的响应。

这是运行良好的测试:

public class TestController : ApiController
{

    [AllowAnonymous]
    [HttpGet]
    public HttpResponseMessage helloWorld()
    {
        return Request.CreateResponse(HttpStatusCode.OK, "HelloWorld!");
    }
}

不工作的控制器:

public class DeviceController : ApiController
{

    [AllowAnonymous]
    [HttpGet]
    public HttpResponseMessage helloWorld() // This returns: "No HTTP resource was found that matches the request URI 'http://api.mySite.com/api/Device/helloWorld'."
    {
        return Request.CreateResponse(HttpStatusCode.OK, "HelloWorld!");
    }

    [AllowAnonymous]
    [HttpPost]
    public HttpResponseMessage Login([FromBody] LoginObject loginObject) // This returns: "NotFound"
    {
        ...
    }

}

这是网络配置:

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(

            name: "API Default",
            routeTemplate: "api/{controller}/{action}/{id}",
            defaults: new { id = RouteParameter.Optional }

        );
    }
}

【问题讨论】:

  • 所以http://api.mySite.com/api/Test/helloWorld 有效,对吧?
  • 是的,我得到了“HelloWorld!”背部。这看起来很奇怪……一定是路由问题?
  • 嗯...让我们检查一下。尝试添加路由属性[Route("api/Device/helloWorld")]
  • 啊,好的,它现在正在工作。我想知道为什么另一个控制器的路由没有明确声明就可以了...随意添加这个作为答案,我会接受它。谢谢!

标签: asp.net-web-api asp.net-web-api-routing


【解决方案1】:

尝试像 acrion 一样添加明确的路由声明

[Route("api/Device/helloWorld")]
[AllowAnonymous]
[HttpGet]
public HttpResponseMessage helloWorld() 

[RoutePrefix("api/Device")]
public class DeviceController : ApiController

然后

[Route("helloWorld")]
[AllowAnonymous]
[HttpGet]
public HttpResponseMessage helloWorld() 

【讨论】:

  • 明确声明路由为我解决了这个问题,谢谢。
【解决方案2】:

对于以后像我这样的可怜虫:确保控制器上的方法是公开的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-12-26
    • 1970-01-01
    • 1970-01-01
    • 2015-02-08
    • 2015-12-06
    • 2012-12-28
    • 2017-05-29
    相关资源
    最近更新 更多