【问题标题】:Web APi Routing UnderstandingWeb APi 路由理解
【发布时间】:2014-10-09 03:25:26
【问题描述】:

我创建了一个名为 WebPortalController 的新控制器,但是当我调用它或尝试通过浏览器调用它时,我无法访问下面的方法,只是说找不到资源。如果需要,是否需要在 RoutesConfig.cs 代码中添加新路由?

namespace WebApi.Controllers
{
public class WebPortalController : ApiController
{
    // GET api/webportal
    private WebPortEnterpriseManagementDa _da = new WebPortEnterpriseManagementDa();


    public ManagedType Get(string name)
    {

        ManagedType items = _da.GetManagedType(name);

        return items;
    }


    // POST api/webportal
    public void Post([FromBody]string value)
    {
    }

    // PUT api/webportal/5
    public void Put(int id, [FromBody]string value)
    {
    }

    // DELETE api/webportal/5
    public void Delete(int id)
    {
    }
}
}

路由文件

namespace WebApi
{
public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );


    }
}

【问题讨论】:

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


【解决方案1】:

您显示的路由配置用于 MVC 路由,位于 App_Start/RouteConfig 文件中。检查您的 App_Start/WebApiConfig 中是否设置了默认 API 路由:

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

然后您需要更改 Get 方法中的参数名称以匹配路由参数:

public ManagedType Get(string id)
{
    ManagedType items = _da.GetManagedType(name);
    return items;
}

这应该允许您通过浏览器调用 Get 方法:

localhost:55304/api/WebPortal/Test

为了测试您的 Post/Put/Delete 方法,您需要使用 Fiddler 或浏览器插件,例如 Postman

【讨论】:

    猜你喜欢
    • 2019-01-20
    • 2016-05-29
    • 1970-01-01
    • 1970-01-01
    • 2021-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多