如何格式化使用嵌套复杂对象的GET uri?

时间:2016-01-22 00:14:36

标签: c# asp.net-web-api get uri complextype

我有以下Get API

public class FooController
{
    public IHttpActionResult Get([FromUri] FooCriteria criteria) { ... }
}

public class FooCriteria
{
    public string Baz { get; set; }

    public Location Location { get; set; }
}

public class Location
{
    public double Latitude { get; set; }

    public double Longitude { get; set; }
}

我不能为我的生活找出Uri的格式来正确传递一个嵌套的复杂类型。

到目前为止,我有http://localhost:8957/api/Foo/?Baz=hello& WHAT GOES HERE

1 个答案:

答案 0 :(得分:0)

这应该是你的网址;

http://localhost:8957/api/Foo/Get?Baz=ThisIsBaz&Location=WebApi.Controllers.FooController%2BLocation

像这样修改你的控制器;

public class FooController : Controller
{
    public IHttpActionResult Get(FooCriteria criteria)
    {          
        return new OkResult(new HttpRequestMessage());
    }

    public ActionResult Index()
    {           
        return View();
    }


    public class FooCriteria
    {
        public string Baz { get; set; }

        public Location Location { get; set; }
    }

    public class Location
    {
        public double Latitude { get; set; }

        public double Longitude { get; set; }
    }
}

然后创建两个视图Called Index和Get

@using WebApi.Controllers
@model WebApi.Controllers.FooController.FooCriteria

@{
    ViewBag.Title = "title";
}
<h2>title</h2>


@Html.ActionLink("Your GET", "Get", new FooController.FooCriteria(){Baz="ThisIsBaz", Location = new FooController.Location(){Latitude = 10, Longitude = 20}})

现在,当您运行时,您应该能够看到ActionLink中URL中传递的内容