【问题标题】:ASP.Net MVC auto slugify RoutesASP.Net MVC 自动 slugify 路由
【发布时间】:2021-09-24 09:07:05
【问题描述】:

我的控制器中有这段代码:

string APIBaseurl = "https://sub.domain.de/";
    [Route("VerseExkurs/Technologien/{technologie}")]
    public async Task<ActionResult> Details(string technologie)
    {
        TechnologieRootobject TechnologieInfo = new TechnologieRootobject();

        using (var client = new HttpClient())
        {
            //Passing service base url  
            client.BaseAddress = new Uri(APIBaseurl);

            client.DefaultRequestHeaders.Clear();
            //Define request data format  
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            //Sending request to find web api REST service resource GetAllEmployees using HttpClient  
            HttpResponseMessage Res = await client.GetAsync("items/technologien/" + technologie + "?access_token=token");

            //Checking the response is successful or not which is sent using HttpClient  
            if (Res.IsSuccessStatusCode)
            {
                //Storing the response details recieved from web api   
                var TechnologieResponse = Res.Content.ReadAsStringAsync().Result;

                //Deserializing the response recieved from web api and storing into the Employee list  
                TechnologieInfo = JsonConvert.DeserializeObject<TechnologieRootobject>(TechnologieResponse);

            }
            //returning the employee list to view  
            return View(TechnologieInfo.data);
        }
    }

但问题是,“{technologie}”变量在某些情况下带有空格。有没有办法自动转换下划线中的空格?

【问题讨论】:

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


    【解决方案1】:

    你的选择很少。

    1. 利用 string.Replace() 方法
        HttpResponseMessage Res = await client.GetAsync("items/technologien/" + technologie.Replace(" ", "_") + "?access_token=token");
    
    1. 编写一个返回正确字符串的辅助函数
    string removeSpaceFromString(string inputString)
    {
         return inputString.Replace(" ", "_"); // or some other method of doing that
    }
    

    【讨论】:

      猜你喜欢
      • 2023-03-24
      • 2011-04-02
      • 2020-04-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-22
      • 1970-01-01
      • 2011-03-28
      相关资源
      最近更新 更多