我试图在WebApi控制器中使用string作为参数。我设置自定义路线如下[路线(" api / sets / {setid}")]但这也没有帮助。控制器代码非常简单,我真的无法得到错误405的问题。这是控制器代码:
public class SetDetails
{
public string ItemDescription { get; set; }
public string ItemName { get; set; }
public string ItemUrl { get; set; }
public string ItemImageUrl { get; set; }
public decimal ItemPrice { get; set; }
}
// GET: api/Sets
[Route("api/sets/{setid}")]
public IQueryable<SetDetails> GetDetails(string setid)
{
var sd = from a in db.Sets
where a.SetID.Contains(setid)
select new SetDetails
{
ItemDescription = a.ItemDescription,
ItemName = a.ItemName,
ItemUrl = a.ItemUrl,
ItemImageUrl = a.ItemImageUrl,
ItemPrice = a.ItemPrice
};
return sd.AsQueryable();
}
这是WebApiConfig
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "PreppApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
var json = config.Formatters.JsonFormatter;
json.SerializerSettings.PreserveReferencesHandling =
Newtonsoft.Json.PreserveReferencesHandling.Objects;
config.Formatters.Remove(config.Formatters.XmlFormatter);
}
}
答案 0 :(得分:1)
不要附加查询字符串参数,而是让WebApi路由将其从URL的最后一部分中拉出来
$.getJSON("/api/sets/" + setid);