网页API 2:最佳实践从控制器返回视图模型数据$ HTTP成功的结果呢? [英] Web API 2 : Best Practice returning ViewModel data from Controller to $http Success result ?

查看:179
本文介绍了网页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);
    }


解决方案

  

请注意,的WebAPI 基于反射的作品,这意味着你花括号{}瓦尔必须在方法相同的名字相匹配。


因此​​,以匹配像 API /库/测试基于默认的模板API / {控制器} / {ID}的样本网址你的方法需要声明如下:

  [HTTPGET]
公共对象GetPhotosForPage(字符串ID){
   返回ID;
}

其中参数字符串currPage 是由字符串ID替换

为什么,因为默认路由声明与名称的参数的原因 ID

  RouteTable.Routes.MapHttpRoute(名称:DefaultApi
                 routeTemplate:API / {}控制器/(编号),
                 默认:新{ID = System.Web.Http.RouteParameter.Optional});

网页API V1定义全球资源在 Global.asax中的Application_Start 事件。假设你正在使用Visual Studio 2013和基于微软默认的模板你的方法可能如下:

 保护无效的Application_Start()
{
    AreaRegistration.RegisterAllAreas();
    GlobalConfiguration.Configure(WebApiConfig.Register);
    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    BundleConfig.RegisterBundles(BundleTable.Bundles);
}

本的WebAPI路由配置中的 WebApiConfig.Register 而MVC配置中出现 RouteConfig.RegisterRoutes <发生/ p>

对于其中引入了一种叫做V2的WebAPI的路线这些属性可以与你的控制器类一起使用并可以方便的路由配置。

例如:

 公共类BookController的:ApiController {
     //其中笔者是一个字母(A-Z)用最少的5个字符和10个最大的。
    [路线(样品/ {ID} / {newAuthor:阿尔法:长度(5,10)})]
    公共图书获取(INT ID,字符串newAuthor){
        返回新图书(){标题=SQL Server 2012的ID =+ ID,作者=阿德里安&安培;+ newAuthor};
    }   [路线(otherUrl / {ID} / {newAuthor:阿尔法:长度(5,10)} / {}标题)]
   公共图书获取(INT ID,字符串newAuthor,串题){
       返回新图书(){标题=SQL Server 2012的ID =+ ID,作者=阿德里安&安培;+ newAuthor};
   }
...

I wonder what's the recommended way to handle data (ViewModels) in Web Api 2.. I have googled around quite much, and found some "recepies" but i wonder what's the most flexible and easy way of handling this..

This call returns error -->

GET http://localhost:63203/api/Gallery/GetPhotosForPage 404 (Not Found)

probably because of some signature error..,.

Here is the $http call (Angular) :

var currPage = $location.path() || "Unknown"; 

$http({
    method: 'GET',
    url: '/api/Gallery/GetPhotosForPage',
    accept: 'application/json',
    data: JSON.stringify(currPage)   //currpage = ex. "/leftwing"
    })
        .success(function (result) {
            console.log(result);
            $scope.mystuff= result;
        });

Here is the Controller GET method : /PriPhotosModel is the viewmodel...

[HttpGet]
    public object GetPhotosForPage(string currPage)
    {
        PhotoServices photoService = new PhotoServices();
        List<PriPhotosModel> priPhotos = photoService.GetPriPhotosForAllPhotographersOnPage(currPage);
        return Request.CreateResponse(HttpStatusCode.OK, priPhotos);
    }

解决方案

Please note that WebApi works based on reflection this means that your curly braces {vars} must match the same name in your methods.

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成功的结果呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆