相关疑难解决方法(0)

我为什么要使用IHttpActionResult而不是HttpResponseMessage?

我一直在使用WebApi进行开发,并已转移到WebApi2,其中Microsoft引入了一个IHttpActionResult似乎建议用于返回a 的新接口HttpResponseMessage.我对这个新接口的优点感到困惑.这似乎主要是公正提供SLIGHTLY更简单的方法来创建一个HttpResponseMessage.

我认为这是"为抽象而抽象"的论点.我错过了什么吗?除了节省一行代码之外,使用这个新接口可以获得什么样的真实优势?

旧方式(WebApi):

public HttpResponseMessage Delete(int id)
{
    var status = _Repository.DeleteCustomer(id);
    if (status)
    {
        return new HttpResponseMessage(HttpStatusCode.OK);
    }
    else
    {
        throw new HttpResponseException(HttpStatusCode.NotFound);
    }
}
Run Code Online (Sandbox Code Playgroud)

新方式(WebApi2):

public IHttpActionResult Delete(int id)
{
    var status = _Repository.DeleteCustomer(id);
    if (status)
    {
        //return new HttpResponseMessage(HttpStatusCode.OK);
        return Ok();
    }
    else
    {
        //throw new HttpResponseException(HttpStatusCode.NotFound);
        return NotFound();
    }
}
Run Code Online (Sandbox Code Playgroud)

c# httpresponse asp.net-web-api

312
推荐指数
6
解决办法
19万
查看次数

从MVC控制器调用Web API

我的MVC5项目解决方案中有一个WebAPI控制器.WebAPI有一个方法,它将特定文件夹中的所有文件作为Json列表返回:

[{"name":"file1.zip", "path":"c:\\"}, {...}]

从我的HomeController我想调用此方法,将Json响应转换为List<QDocument>并将此列表返回到Razor视图.此列表可能为空:[]如果文件夹中没有文件.

这是APIController:

public class DocumentsController : ApiController
{
    #region Methods
    /// <summary>
    /// Get all files in the repository as Json.
    /// </summary>
    /// <returns>Json representation of QDocumentRecord.</returns>
    public HttpResponseMessage GetAllRecords()
    {
      // All code to find the files are here and is working perfectly...

         return new HttpResponseMessage()
         {
             Content = new StringContent(JsonConvert.SerializeObject(listOfFiles), Encoding.UTF8, "application/json")
         };
    }               
}
Run Code Online (Sandbox Code Playgroud)

这是我的HomeController:

public class HomeController : Controller
{
     public Index()
     {
      // I want to …
Run Code Online (Sandbox Code Playgroud)

c# asp.net-mvc asp.net-web-api

23
推荐指数
3
解决办法
10万
查看次数

MVC 4 Web API Action返回:Types vs HttpResponseMessage

返回类型有什么区别,例如

    public class MyController : ApiController
    {
        public IEnumerable<MyType> Get()...
Run Code Online (Sandbox Code Playgroud)

VS

返回HttpResponseMessage:

    public class MyController : ApiController
    {
        public HttpResponseMessage Get()...
Run Code Online (Sandbox Code Playgroud)

??

MVC是否将类型包装到HttpResponseMessage内容对象中?除非明确添加格式化程序,否则页面上的结果看起来相同.

客户有什么不同?

asp.net action asp.net-web-api

13
推荐指数
1
解决办法
5063
查看次数

asp.net webapi控制器,返回类型实体或HttpResponseMessage

我想知道在我的ApiController中使用HttpResponseMessage作为返回类型有什么好处?比较直接返回键入的实体或集合.

我们试图确定一个实践,以保持我们正在进行的项目的一致性.

asp.net-web-api

11
推荐指数
1
解决办法
3018
查看次数