首页 > 解决方案 > how to specifiy web api route

问题描述

I am trying to call the api action method using HttpClient. This is my api controller:

[RoutePrefix("api/v1/OrganizationUnit")]
    public class OrganizationUnitController : ApiController
    {
        public IOrganizationUnitRepository OrganizationUnitRepository;

        [Route("{id}")]
        [ResponseType(typeof(OrganizationUnit))]
        [HttpGet]
        public IHttpActionResult Get(string id)
        {
            return Ok(OrganizationUnitRepository.Get(id));
        }

        [ResponseType(typeof(OrganizationUnit))]
        [HttpGet]
        [Route("")]
        public IHttpActionResult GetAll()
        {
            return Ok(OrganizationUnitRepository.GetAll());
        }

        [ResponseType(typeof(OrganizationUnit))]
        [HttpGet]
        [Route("GetAllOU")]
        public IHttpActionResult GetAllOrganizationUnits()
        {
            return Ok(OrganizationUnitRepository.GetAllOrganizationUnits());
        }
}

Below is the Route config:

config.MapHttpAttributeRoutes();

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

And in the MVc controller I am calling this API, like:

using (var client = new HttpClient())
            {
                var organizationUnitUrl = Url.RouteUrl("DefaultApi", new { httpRoute = "", controller = "OrganizationUnit" }, Request.Url.Scheme);
                string requestUrl = organizationUnitUrl.ToString() + "/GetAllOU";
                var responseTask = client.GetAsync(requestUrl);
                responseTask.Wait();
                var result = responseTask.Result;

            if (result.IsSuccessStatusCode)
            {
                var readTask = result.Content.ReadAsAsync<IEnumerable<OUWrapper>>();
                readTask.Wait();
                organizationUnitList = readTask.Result.ToList();
            }
        }

I want to call the action GetAllOrganizationUnits which has Route specified as "GetAllOU". As you can see, I am appending the "GetAllOU" to the url when calling the api using HttpClient. I think there has to be a good way in which I can call this api without appending anything to URL. Is there a way where I can specifiy the Route "GetAllOU" and call the action?

Any help appreciated.

标签: c#asp.net-web-api

解决方案


愿这对您有所帮助,以简单易行的方式为客户提供服务。

    private HttpClient _simpleserviceClient;

    private const string _getUri = "/ROUTE_TO_ACTION/{0}";
    private const string _postUri = "/ROUTE_TO_ACTION";

    public ReturnModel Postdata(SomeModel model)
    {
        var uri = string.Format(_postUri );
        var response = ServiceClient().PostAsJsonAsync(uri, model).Result;
        var result = response.Content.ReadAsAsync<ReturnModel>().Result;
        return result;
    }

    public ReturnModel getdata(int id)
    {
        var uri = string.Format(_getUri ,id);
        var response = ServiceClient().GetAsync(uri).Result;
        var result = response.Content.ReadAsAsync<ReturnModel>().Result;
        return result;
    }

    private HttpClient ServiceClient()
    {
        var client= _simpleserviceClient ?? new HttpClient();
        client.BaseAddress = new Uri("YOUR_BASE_URL_TO_API");   //"http://localhost:8080/"
        client.Timeout = TimeSpan.FromMinutes(3);
    }

推荐阅读