在asp.net web api中添加一个额外的get方法

Add an extra get method in asp.net web api

本文关键字:一个 方法 get web net asp api 添加      更新时间:2023-09-26

我是asp.net web api世界的新手。我对get()、put()、post()和delete有了基本的理解。

在我的应用程序中,我还需要两个get()方法。下面给出了一个解释-

public class StudentController : ApiController 
{
    public IEnumerable Get()
    {
        //returns all students.
    }
    //I would like to add this method=======================
    [HttpGet]
    public IEnumerable GetClassSpecificStudents(string classId)
    {
        //want to return all students from an specific class.
    }
    //I also would like to add this method=======================
    [HttpGet]
    public IEnumerable GetSectionSpecificStudents(string sectionId)
    {
        //want to return all students from an specific section.
    }
    public Student Get(string id) 
    {
         //returns specific student.
    }
}

angularjs控制器中已经存在一个$http.get(..)

我的问题是,如何从角度控制器调用另外两个get()方法。

嗯,我已经很久没有使用asp.net mvc了。但你可以做一些类似的事情:

 public class StudentController : ApiController 
 {
    [Route("students")]
    public IEnumerable Get()
    {
    //returns all students.
    }
    //I would like to add this method=======================
    [HttpGet]
    [Route("students/class/{classId}")]
    public IEnumerable GetClassSpecificStudents(string classId)
    {
        //want to return all students from an specific class.
    }
    //I also would like to add this method=======================
    [HttpGet]
    [Route("students/section/{sectionId}")]
    public IEnumerable GetSectionSpecificStudents(string sectionId)
    {
        //want to return all students from an specific section.
    }
    [Route("students/{id}")]
    public Student Get(string id) 
    {
         //returns specific student.
    }
}

您也可以在routeconfig中指定如下路线:

routes.MapRoute(
    name: "students",
    url: "students/class/{classId}",
    defaults: new { controller = "Student", action = "GetClassSpecificStudents", id = UrlParameter.Optional }
);

你必须为你自己努力。你可以在这里和这里阅读更多关于它的信息。

并不是说你有指定的路线,你可以为每条路线添加有角度的$http.gets。

var url = "whateverdoma.in/students/"
$http.get(url)
   .success()
   .error()
var url = "whateverdoma.in/students/class/" + classId;
$http.get(url)
   .success()
   .error()
var url = "whateverdoma.in/students/filter/" + filterId;
$http.get(url)
   .success()
   .error()

您要做的是编写costum angular resource方法,以调用您的API。

  1. 使用angular$resource而不是$http->它是更常见的用法(并且更面向REST:$resource包装$http用于RESTful web API场景)。

  2. 阅读

  3. 了解如何将资源添加到$resource服务。

    这里有一个例子:

    .factory('Store', function ($resource, hostUrl) {
    var url = hostUrl + '/api/v3/store/';
    return $resource("", {  storeId: '@storeId' }, {            
        getSpecific: {
            method: 'GET',
            url: hostUrl + '/api/v3/store-specific/:storeId'
        }
    });
    

    })