简体   繁体   English

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

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

So there is a heap of examples around but finding ones that are relevant to the rtm bits seems to be a little harder to find. 因此,周围有很多示例,但是要找到与rtm位相关的示例似乎有点困难。

I have 2 projects one is an WebApi & the other is MVC4 .net 4.5 application. 我有2个项目,一个是WebApi,另一个是MVC4 .net 4.5应用程序。

I want to make a make an update to an item 我想对商品进行更新

I have a controller within my API that does something like 我的API中有一个控制器,其功能类似于

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

Is this correct? 这个对吗? should I be using a HttpResponseMessage instead of just using my MyModel class? 我应该使用HttpResponseMessage而不是仅使用MyModel类吗? I want to return the correct httpstatus details as much as possible as I am wanting to open up this api to 3rd parties not just my application 我想尽可能地返回正确的httpstatus详细信息,因为我想向第三方开放此api,而不仅仅是我的应用程序

Calling this api from my mvc application from my controller how do I do this? 从我的控制器的mvc应用程序调用此api,我该怎么做?

The beste way is to use HttpResponseMessage like this: 最好的方法是使用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);;
}

I mostly use EasyHttp if I want want to call a WebApi method from my MVC app: 如果要从我的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);

If you want to respond with httpstaus code you have to return HttpResponseMessage. 如果要使用httpstaus代码进行响应,则必须返回HttpResponseMessage。

You may choose to have a common method returning your BOs and call it from the Action and from your other mvc application code. 您可以选择一种返回BO的通用方法,然后从Action和其他mvc应用程序代码中调用它。 Then your rest calls would always be wrapped with a status code and other calls get an object. 这样,您的其余呼叫将始终被状态代码包裹起来,而其他呼叫将得到一个对象。

[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