简体   繁体   中英

Determine URL prior to routing in controller for asp.net core

I am developing an asp.net core site, and I have a controller class which gets data for an api that I am using (jquery datatable).

ClientController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using GuptaAccounting.Data;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Extensions;
using Microsoft.AspNetCore.Mvc;

namespace GuptaAccounting.Controllers
{
    //Need to add the route so server knows which path/url to go to
    [Route("api/Client")]
    //State that this is an api controller
    [ApiController]
    public class ClientController : Controller
    {
        private readonly ApplicationDbContext _db;

        public ClientController(ApplicationDbContext db)
        {
            _db = db;
        }

        [HttpGet]
        public IActionResult GetAll()
        {
            return Json(new
            {
                data = _db.Client.Where(Client => Client.IsConsultationClient == false).ToList()
            });
        }
    }
}

I need to know where I am on the site, prior to routing to "api/client" so that i can return different data in the GetAll function (returning clients where IsConsultationClient == true). How would I do this? I have already tried to use IHttpContextAccessor and i didn't have any luck.

[EDIT]

I am making an ajax call from a js file. Here is part of my code

 dataTable = $('#DT_load').DataTable({ //need to make an ajax call using the api that i included "ajax": { "url": "/api/client", //this is a get request "type": "GET", "datatype": "json" },

Maybe this will work.

In controller:

[HttpGet]
[MyRouter]
public IActionResult GetAll(bool isConsultationClient = false)
{
    return Json(new
    {
        data = _db.Client
            .Where(Client => Client.IsConsultationClient == isConsultationClient).ToList()});
    }
}

In AttributeFilter:

public class MyRouterAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext context)
    {
        if (context.HttpContext.Request.Headers
                .TryGetValue("IsConsultationClient", out var isConsultationClient))
        {
            if (isConsultationClient== "Yes")
                context.ActionArguments.Add("isConsultationClient", true);
            else if (isConsultationClient== "No")
                context.ActionArguments.Add("isConsultationClient", false);
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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