URL路由作为MVC .Net核心中的API的文件夹的所有控制器

时间:2018-05-21 15:21:08

标签: asp.net-mvc routing asp.net-mvc-routing

我必须在所有Web API上定义以下内容。

 $company_id=$_POST['company']:
    $query="SELECT `contact_company`.`contact_id`, CONCAT(`surname`,' ',`fname`), `contact_company`.`company_id` FROM `seta`.`contact_company` AS `contact_company`, `seta`.`contacts` AS `contacts` WHERE `contact_company`.`contact_id` = `contacts`.`contact_id` AND `contact_company`.`company_id` ='".$company_id."' ";

    $result=mysqli_query($connection,$query) or die ("Query to get data from contact_company table failed: ".mysqli_connect_error());


    while ($row=mysqli_fetch_array($result)) {
        $contact_id=$row["contact_id"];
        $company_id=$row["company_id"];
        $contact_name=$row["CONCAT(`surname`,' ',`fname`)"];

        echo "<option value=\"$contact_id\">
             $contact_name
             </option>";
        }

如何将其定义为特定文件夹中的默认值。

假设我有 API 文件夹。我想在该文件夹的所有控制器上设置这些属性(或不想写)。

如何在.Net核心MVC中定义这种路由?

1 个答案:

答案 0 :(得分:1)

转到App_Start文件夹WebApiConfig.cs并将此代码放在那里,因此它将全局应用于所有控制器和操作方法。 你可以在项目中调用它 http://localhost/API/ControllerName/MethodName?parameters

    config.Routes.MapHttpRoute("DefaultApiWithId", "Api/{controller}/{id}", new { id = RouteParameter.Optional }, new { id = @"\d+" });
    config.Routes.MapHttpRoute("DefaultApiWithAction", "Api/{controller}/{action}");
    config.Routes.MapHttpRoute("DefaultApiGet", "Api/{controller}", new { action = "Get" }, new { httpMethod = new HttpMethodConstraint(HttpMethod.Get) });
    config.Routes.MapHttpRoute("DefaultApiPost", "Api/{controller}", new { action = "Post" }, new { httpMethod = new HttpMethodConstraint(HttpMethod.Post) });