MVC Web 中的路由 Api

Routing in MVC Web Api

我想在 mvc 中从 Api 获取一些数据。

这是客户端

        public List<UserType> SearchUserType(string text)
    {

        HttpWebRequest wr = (HttpWebRequest)WebRequest.Create("http://localhost:3852/api/Default1/" + text);
        wr.Method = "GET";

        HttpWebResponse response = (HttpWebResponse)wr.GetResponse();
        Stream r_stream = response.GetResponseStream();
        StreamReader response_stream = new StreamReader(r_stream, System.Text.Encoding.GetEncoding("utf-8"));
        var s = new System.Web.Script.Serialization.JavaScriptSerializer();
        return s.Deserialize<List<UserType>>(response_stream.ReadToEnd());
    }

我从 textBox 收到 Text。 这是我的 Api

        public List<UserType> Get(string userTypeName)
    {
        return (from c in bl.Select() where c.UserTypeName.Contains(userTypeName) select c).ToList<UserType>();
    }

我认为我的路由有误。这是我在 RouteConfig.cs 中的路由。

 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 }
        );

    }

我应该对 RouteConfig.cs 进行哪些更改才能正常工作。 这是我的 WebApiConfig.csclass.

 public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}

我改变了它们并成功了。 这是请求

  HttpWebRequest wr = (HttpWebRequest)WebRequest.Create("http://localhost:3852/api/default1/Get/" + text);

这是WebApiConfig

  public static void Register(HttpConfiguration config)
    {
        config.Routes.MapHttpRoute(
            name: "SearchApi",
            routeTemplate: "api/{controller}/{action}/{usertypename}",
            defaults: new { usertypename = RouteParameter.Optional }

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

        );
    }