简体   繁体   中英

Can't use object as parameter in WebAPI get request

I have a C# class called DateParams defined as follows:

    public class DateParams {
        public DateTime StartDate { get; set; }
        public DateTime EndDate { get; set; }
    }

In my controller I have a Get method defined as:

    [HttpGet]
    [Route("api/myreport/{dateParams}")]
    public HttpResponseMessage Get([FromUri]DateParams dateParams) {}

I'm calling the controller from Angular as follows:

  myService.GetMyReport = function (dateParams) {
      return $http.get(serviceURLRoot + 'api/myreport/', dateParams, { withCredentials: true }).success(function (data) {
      });
  };

I keep getting the error: The requested resource does not support http method 'GET'.

I've verified that dateParams matches the structure defined server side and it's properly populated. Similar questions on StackOverflow refer to using [FromUri] in the controller method's parameter list but this hasn't resolved the issue. I tried [FromBody] as well but it also fails, probably because Get requests can't have bodies.

Give this a try. This has worked for me in the past

[System.Web.Http.AcceptVerbs("GET")]
[System.Web.Http.HttpGet]
[Route("api/myreport/{dateParams}")]
public HttpResponseMessage Get([FromUri]DateParams dateParams) {}

You are probably using System.Web.Mvc namespace

I've seen this a couple of times with DateTime format, a better approach might be to define them as string in your object and parse it to a date in your code/model.

For testing, try the "string" and see if that works, then if you still need to have the model defined with DateTime type, there are a few rules to be followed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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