API无法识别ApiController

问题描述 投票:0回答:2

我在访问我的ApiController时遇到问题。当我进行API调用时,我得到以下响应:

{
    "Message": "No HTTP resource was found that matches the request URI 'http://localhost/myapp/api/data/abc'.",
    "MessageDetail": "No action was found on the controller 'Data' that matches the request."
}

我想在TopShelf服务上创建一个OWIN Web API,在那里我可以获得一些数据。我是新手,所以我希望有人可以向我解释一下,我做错了什么。它看起来像我看不见的东西。

开始:

var apiHostConfiguration = new Dictionary<string, WebApiHostConfig> {{"webApi", new WebApiHostConfig {Endpoint = "/myapp" ,RequiresOAuth = false}}};
// Start OWIN host 

const string baseAddress = "http://localhost";
foreach (var conf in apiHostConfiguration)
{
    var app = new WebApiApp();
    var opt = new StartOptions(baseAddress + conf.Value.Endpoint);
    OwinApps.Add(WebApp.Start(opt, app.Configuration));
}

ApiConfig:

class WebApiApp
{
    public void Configuration(IAppBuilder appBuilder)
    {
        var config = new HttpConfiguration();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{action}/",
            defaults: new {}
        );
        config.Formatters.Clear();
        config.Formatters.Add(new JsonMediaTypeFormatter());
        config.EnableCors();
        config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;
        appBuilder.UseWebApi(config);
    }
}

控制器:

[EnableCors("*", "*", "*")]
public class DataController : ApiController
{
    [HttpGet]
    public string Abc(string text)
    {
        var name = GetType().Name;
        return $"{name} pings back «{text}»";
    }
}

API调用:

http://localhost/myapp/api/data/abc
c# rest api owin
2个回答
0
投票

问题就像@AluanHaddad在我的问题下面的评论说,我没有将string text从我的行动定义到路线。

评论:

Your route template does not include an optional parameter. 
It is also not very restful FWIW. 
Try 
    routeTemplate: "api/{controller}/{action}/{text?}", 
    defaults: new {text = RouteParameter.Optional} 
but consider that 
    routeTemplate: "api/{controller}/{text?}", 
    defaults: new {text = RouteParameter.Optional} 
is likely preferable.

谢谢你分享。


-1
投票

更换

本地主机

使用分配给运行Web服务/ API的系统的PRIVATE IP

并出口

你可以找到你的私人IP

在命令提示符下键入ipconfig / all:如果您在Windows上 在命令提示符下键入ifconfig:如果您在mac上

© www.soinside.com 2019 - 2024. All rights reserved.