API无法识别ApiController

时间:2017-12-31 22:20:41

标签: c# rest api owin

访问我的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

2 个答案:

答案 0 :(得分: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 :(得分:-1)

替换

  

本地主机

将您的私有IP分配给运行Web服务/ API的系统

  

http://192.168.8.100

你可以找到你的私人IP

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