C#Net Core 2.0重构

为控制器编写代码可能导致一次又一次地重复自己。


如何重用下面的代码并将DRY原理应用于C#Net Core 2.0。MVC控制器?


请参见以下示例。


使用EF和Web API获取部门的完整列表的代码如下。


[HttpGet]

public async Task<IActionResult> Department()

{


    using (var client = await _apiHttpClient.GetHttpClientAsync())

    {

        var response = await client.GetAsync("api/Department");


        if (response.IsSuccessStatusCode)

        {

            var content = await response.Content.ReadAsStringAsync();

            var dptos = JsonConvert.DeserializeObject<Department[]>(content);


            return View(dptos);

        }


        if (response.StatusCode == HttpStatusCode.Unauthorized || response.StatusCode == HttpStatusCode.Forbidden)

            return RedirectToAction("AccessDenied", "Authorization");


        throw new Exception($"A problem happened while calling the API: {response.ReasonPhrase}");

    }

}

确实只有一个部门几乎是相同的。


[HttpGet]

public async Task<IActionResult> DeparmentEdit(string id)

{

    ViewData["id"] = id;


    using (var client = await _apiHttpClient.GetHttpClientAsync())

    {

        var response = await client.GetAsync($"api/Department/{id}");


        if (response.IsSuccessStatusCode)

        {

            var content = await response.Content.ReadAsStringAsync();

            var dpto = JsonConvert.DeserializeObject<Department>(content);


            return View(dpto);

        }


        if (response.StatusCode == HttpStatusCode.Unauthorized || response.StatusCode == HttpStatusCode.Forbidden)

            return RedirectToAction("AccessDenied", "Authorization");


        throw new Exception($"A problem happened while calling the API: {response.ReasonPhrase}");

    }

}

_apiHttpClient字段包含HttpClient的自定义实现,用于令牌和刷新令牌以访问Web API。


我认为在这里应用重构和DRY无关紧要,但是无论如何,我将在下面复制他的实现。


无线电通信局,并预先感谢您的答复。


智慧大石
浏览 146回答 2
2回答
打开App,查看更多内容
随时随地看视频慕课网APP