本文介绍了网页API 2:最佳实践从控制器返回视图模型数据$ HTTP成功的结果呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道什么是在网页API 2处理数据(的ViewModels)推荐的方式..我用Google搜索周围颇多,并发现了一些recepies但我不知道什么是处理这种最灵活和最简单的方法..

此调用返回的错误 - >

  GET HTTP://本地主机:63203 / API /库/ GetPhotosForPage 404(未找到)

可能是因为一些签名错误..,。

下面是$ HTTP调用(角):

  VAR currPage = $ location.path()|| 未知;$ HTTP({
    方法:GET,
    网址:'/ API /库/ GetPhotosForPage',
    接受:应用/ JSON,
    数据:JSON.stringify(currPage)// currpage =前。 /左翼
    })
        .success(功能(结果){
            的console.log(结果);
            $ scope.mystuff =结果;
        });

下面是控制器GET方法:/ PriPhotosModel是视图模型...

  [HTTPGET]
    公共对象GetPhotosForPage(字符串currPage)
    {
        PhotoServices照片服务=新PhotoServices();
        清单< PriPhotosModel> priPhotos = photoService.GetPriPhotosForAllPhotographersOnPage(currPage);
        返回Request.CreateResponse(的HTTPStatus code.OK,priPhotos);
    }


解决方案

Therefore to match a sample URL like api/gallery/test based on the default template "api/{controller}/{id}" Your method needs to be declared like this:

[HttpGet]
public object GetPhotosForPage(string id){
   return id;
}

Where the parameter string currPage was replaced by string id.

The reason why is because the default routing declares the parameter with name id :

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

Web Api v1 defines resources globally in the global.asax on application_start event. Assuming you are using Visual Studio 2013 and based Microsoft default template your method may look like this:

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();
    GlobalConfiguration.Configure(WebApiConfig.Register);
    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    BundleConfig.RegisterBundles(BundleTable.Bundles);
}

The WebApi routing configuration occurs in the WebApiConfig.Register while the MVC configuration occurs in the RouteConfig.RegisterRoutes

Regarding WebApi v2 which introduced something called Route Attributes those can be used along with your Controller class and can facilitate the routing configuration.

For example:

 public class BookController : ApiController{
     //where author is a letter(a-Z) with a minimum of 5 character and 10 max.
    [Route("sample/{id}/{newAuthor:alpha:length(5,10)}")]
    public Book Get(int id, string newAuthor){
        return new Book() { Title = "SQL Server 2012 id= " + id, Author = "Adrian & " + newAuthor };
    }

   [Route("otherUrl/{id}/{newAuthor:alpha:length(5,10)}/{title}")]
   public Book Get(int id, string newAuthor, string title){
       return new Book() { Title = "SQL Server 2012 id= " + id, Author = "Adrian & " + newAuthor };
   }
...

这篇关于网页API 2:最佳实践从控制器返回视图模型数据$ HTTP成功的结果呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-22 22:16
查看更多