简体   繁体   English

为什么我的Web Api 2 Post方法没有被点击?

[英]Why is my Web Api 2 Post method not hit?

In my apicontroller I have 2 methods which can handle Post requests: 在我的apicontroller中,我有2种方法可以处理Post请求:

public WatchListItemDTO Post(MovieDto movie)
{
    //do smt..
}

[HttpPost]
[Route("MarkMovieAsWatched/{id}")]
public void MarkMovieAsWatched(int id)
{
    // do smt..
}

The controller has prefix attribute: [RoutePrefix("api/DownloadList")] . 控制器具有前缀属性: [RoutePrefix("api/DownloadList")] When I make a (post) request to http://localhost:4229/api/DownloadList/MarkMovieAsWatched/ it hits my Post method. 当我向http://localhost:4229/api/DownloadList/MarkMovieAsWatched/发出(发布)请求时,它命中了我的Post方法。 The request also contains an object: {id: 12} . 该请求还包含一个对象: {id: 12}

My WebApiConfig : 我的WebApiConfig

public static void Register(HttpConfiguration config)
{
    config.EnableCors();

    config.MapHttpAttributeRoutes();

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

    // To disable tracing in your application, please comment out or remove the following line of code
    // For more information, refer to: http://www.asp.net/web-api
    config.EnableSystemDiagnosticsTracing();
}

Could someone explaint to me why the method MarkMovieAsWatched is not hit? 有人可以向我解释为什么没有点击MarkMovieAsWatched方法吗? And how to solve this? 以及如何解决呢?

It might be that your route requires an id as part of the route. 您的路线可能需要ID作为路线的一部分。

Try changing your attribute to: 尝试将属性更改为:

[Route("MarkMovieAsWatched/{id?}")]

That way if you don't pass the id as part of the path, the route will still be a valid match. 这样,如果您不将ID作为路径的一部分传递,则路由仍将是有效的匹配项。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM