繁体   English   中英

从mvc4应用程序调用WebApi RTM的正确方法

[英]Correct way to call WebApi RTM from an mvc4 application

因此,周围有很多示例,但是要找到与rtm位相关的示例似乎有点困难。

我有2个项目,一个是WebApi,另一个是MVC4 .net 4.5应用程序。

我想对商品进行更新

我的API中有一个控制器,其功能类似于

    [HttpPut]
    public MyModel Update(MyModel model)
    {
        //make update
        return model;
    }

这个对吗? 我应该使用HttpResponseMessage而不是仅使用MyModel类吗? 我想尽可能地返回正确的httpstatus详细信息,因为我想向第三方开放此api,而不仅仅是我的应用程序

从我的控制器的mvc应用程序调用此api,我该怎么做?

最好的方法是使用HttpResponseMessage,如下所示:

[HttpPut]
public HttpResponseMessage Update(MyModel model)
{
    if(notfound)
    {
      return this.Request.CreateResponse(HttpStatusCode.NotFound);
    }

    //make update
    return this.Request.CreateResponse<MyModel>(HttpStatusCode.OK, Model);;
}

如果要从我的MVC应用程序调用WebApi方法,我主要使用EasyHttp

var model = new ExpandoObject(); // or use a stronly typed class.
model.Id = 1,
model.Name = "foo"

var http = new HttpClient();
http.Post("url", model, HttpContentTypes.ApplicationJson);

如果要使用httpstaus代码进行响应,则必须返回HttpResponseMessage。

您可以选择一种返回BO的通用方法,然后从Action和其他mvc应用程序代码中调用它。 这样,您的其余呼叫将始终被状态代码包裹起来,而其他呼叫将得到一个对象。

[HttpPut]
public MyModel Update(MyModel model)
{
    return base.Request.CreateResponse<MyModel>(HttpStatusCode.OK, UpdateModel(model));;
}

[NonAction]
internal MyModel UpdateModel(MyModel model)
{
    //make update
    return model;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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