🙂 İNSANLARIN EN HAYIRLISI INSANLARA FAYDALI OLANDIR 🙂

Ramazan HABER / C# Web Api MVC RMOS / Rest Web Api Mvc ve Swagger

1-) C# Web Api MVC RMOS - Rest Web Api Mvc ve Swagger

 

 client.DefaultRequestHeaders.Authorization =new AuthenticationHeaderValue("Bearer", token);

 

 

ÖNEMLİ AJAX İLE POST GET İÇİN CORS U AKTİF ET : https://www.roketnot.com/not/1570-web-api-2-ajax-cors-hatasi-giderme-enable-enabling-cors

 

 

ÖNEMLİ APİNİN SÜREKLİ ÇALIŞMASI İÇİN BUNU YAP : https://www.roketnot.com/not/1573-web-api-timer-kullanimi-ve-iis-de-surekli-calismasi-making-aspnet-application-always-running

 

 

Install-Package Swashbuckle

 

https://localhost:44381/swagger VEYA https://localhost:44381/swagger/ui/index

 

kaynak : http://www.canertosuner.com/post/web-api-projelerine-swagger-ekleme

kaynak video : https://www.youtube.com/watch?v=tyesYzBnS4A&ab_channel=KasamShaikh

 

 

Metodun veya Controller'in SWAGER DE GÖZÜKMESİNİ İSTEMİYORSAN BUNU YAPARSIN

 

[ApiExplorerSettings(IgnoreApi = true)]

[Route("order/{remoteId}")]

public HttpResponseMessage order(){}

 

 

İstek olarak gelen Bearer Token değerini alma

 

[Route("order/{remoteId}")]

public HttpResponseMessage order(){

 string token = "";

 try

 {

  var headers = Request.Headers;

  if (headers.Contains("Authorization")) token = headers.GetValues("Authorization").First();

 }

 catch { }}

 

token içindeki değerleri okumak

public JwtPayload GetPayload(string token)

{

 var handler = new JwtSecurityTokenHandler();

 var tokenData = handler.ReadJwtToken(token);

 return tokenData.Payload; } //tokenData.Header

 

 

STEP 1

STEP 2

STEP 3

STEP 4

 

 

STEP 5

AŞAĞIDAKİNİ YAZIP ENTER'E BAS EKLER

 

Install-Package Swashbuckle

 

 

STEP 6

AŞAĞIDAKİ GİBİ ERİŞEBİLİRSİN

 

https://localhost:44381/swagger VEYA https://localhost:44381/swagger/ui/index

 

 

STEP 7

 

       // POST api/values

        public string Post([FromBody] string value)

        {

            return "value";

        }

 

STEP 8

 

 

STEP 9 -> Views-> Shared -> _Layout.cshtml

 

swagger linkini eklemek için bu şekilde değiştir

 

 

<!DOCTYPE html>

<html>

<head>

    <meta charset="utf-8" />

    <meta name="viewport" content="width=device-width" />

    <title>@ViewBag.Title</title>

    @Styles.Render("~/Content/css")

    @Scripts.Render("~/bundles/modernizr")

</head>

<body>

    <div class="navbar navbar-inverse navbar-fixed-top">

        <div class="container">

            <div class="navbar-header">

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">

                    <span class="icon-bar"></span>

                    <span class="icon-bar"></span>

                    <span class="icon-bar"></span>

                </button>

                @Html.ActionLink("Application name", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })

            </div>

            <div class="navbar-collapse collapse">

                <ul class="nav navbar-nav">

                    <li>@Html.ActionLink("Home", "Index", "Home", new { area = "" }, null)</li>

                    <li>@Html.ActionLink("API", "Index", "Help", new { area = "" }, null)</li>

                    <li>@Html.ActionLink("SWAGGER API", "Index", "swagger/ui/index", routeValues: new { Area = "" }, htmlAttributes: new { id = "index" })</li>

                </ul>

            </div>

        </div>

    </div>

    <div class="container body-content">

        @RenderBody()

        <hr />

        <footer>

            <p>&copy; @DateTime.Now.Year - My ASP.NET Application</p>

        </footer>

    </div>

 

    @Scripts.Render("~/bundles/jquery")

    @Scripts.Render("~/bundles/bootstrap")

    @RenderSection("scripts", required: false)

</body>

</html>

 

STEP 10 -> App_Start -> WebApiConfig.cs -> aşağıdakini ekle

 

 

 config.Formatters.JsonFormatter.SerializerSettings = new JsonSerializerSettings();

 

 

> metot aşağıdakigibi olacak

 

 //[System.Web.Mvc.Route("api/Barkod/GetCari/{plan_kod}")]

        public HttpResponseMessage GetCari(string plan_kod)

        {

            DataTable dt = RHVeritabani.MyGetDataTable("select Plan_Id,plan_kod,plan_ad from muh_plan where Plan_Grup=2 and plan_kod='320.01.U005'");

            return Request.CreateResponse(HttpStatusCode.OK, dt);

        }

 

> WebApiConfig.cs (yandaki gibi ayarla routeTemplate: "api/{controller}/{action}/{id}",)

 

 public static void Register(HttpConfiguration config)

        {

            // Web API configuration and services

            // Configure Web API to use only bearer token authentication.

            config.SuppressDefaultHostAuthentication();

            config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));

 

            config.Formatters.JsonFormatter.SupportedMediaTypes

    .Add(new MediaTypeHeaderValue("text/html"));

 

            // Web API routes

            config.MapHttpAttributeRoutes();

 

            config.Routes.MapHttpRoute(

                name: "DefaultApi",

                routeTemplate: "api/{controller}/{action}/{id}",

                defaults: new { id = RouteParameter.Optional }

            );

        }

 

  

STEP 11 -> Views -> Home-> Index.cshtml ->aşağıdaki gibi düzenle

 

<div class="jumbotron">

    <h4>

        <b>1- @ViewBag.txtCrm </b>

        <br />

        <br />

        <b>2- @ViewBag.txtOrder</b>

        <br />

        <br />

        <b>3- @ViewBag.txtFront</b>

        <br />

        <br />

        <b>4- @ViewBag.txtMuh</b>

        <br />

        <br />

        <b>5- @ViewBag.txtBack</b>

    </h4>

    <h3>

        <b> Versiyon =  v0.0.1</b>

        <br /><br />

    </h3>

    <div >

        @Html.ActionLink("GUEST X SWAGGER API", "Index", "swagger/ui/index", routeValues: new { Area = "" }, htmlAttributes: new { id = "index", @class = "btn btn-primary btn-lg" })

    </div>

</div>

 

 

 

 

STEP 12 -> Web.config ->aşağıdaki gibi düzenle

 

<configuration>

  <appSettings>

    <add key="webpages:Version" value="3.0.0.0" />

    <add key="webpages:Enabled" value="false" />

    <add key="ClientValidationEnabled" value="true" />

    <add key="UnobtrusiveJavaScriptEnabled" value="true" />

 

 <add key="BackServer" value="RAMBO3" />

 <add key="BackDb" value="Back2019" />

 <add key="BackUser" value="sa" />

 <add key="BackPass" value="sqlşifresi" />

 

  </appSettings>

  <system.web>

 

STEP 13 -> TableEntitiest.Context.cs ->aşağıdaki gibi düzenle

 

public partial class CrmEntities : DbContext

    {

        public CrmEntities()

            : base("name=CrmEntities")

        {

        }

 

        public CrmEntities(string server, string veritab, string user, string sifre)

     : base("metadata=res://*;"

 + "provider=System.Data.SqlClient;"

 + "provider connection string=';"

+ "Data Source=" + server + ";"

+ "Initial Catalog=" + veritab + ";"

+ "Persist Security Info=True;"

+ "User ID=" + user + ";Password=" + sifre + ";"

+ "MultipleActiveResultSets=True';")

        {

        }

 

STEP 14 -> HomeController.cs -> aşağıdaki gibi düzenle

 

public class HomeController : Controller

    {

        public ActionResult Index()

        {

            ViewBag.Title = "Home Page";

            ViewBag.txtCrm = crmAktifmi();

            return View();

        }

        public string crmAktifmi()

        {

            try

            {

                string CrmServer = System.Configuration.ConfigurationManager.AppSettings["CrmServer"];

                string CrmDb = System.Configuration.ConfigurationManager.AppSettings["CrmDb"];

                string CrmUser = System.Configuration.ConfigurationManager.AppSettings["CrmUser"];

                string CrmPass = System.Configuration.ConfigurationManager.AppSettings["CrmPass"];

                CrmEntities db = new CrmEntities(CrmServer, CrmDb, CrmUser, CrmPass);

 

                string backAktifMi = db.Database.SqlQuery<string>("SELECT DB_NAME() as MyDataBaseName").FirstOrDefault();

 

                return  backAktifMi + " Aktif";

            }

            catch (Exception ex)

            {

                return "Crm Web.config Hata !";

            }

        }

 

STEP 15 -> App_Start -> RouteConfig.cs -> anasayfayı swagger yapmak için

 

using Swashbuckle.Application;

using System.Web.Http;

using System.Web.Mvc;

using System.Web.Routing;

 

namespace GuestApi

{

    public class RouteConfig

    {

        public static void RegisterRoutes(RouteCollection routes)

        {

            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

 

            

            // aşağı kod anasayfayı swagger yapar

            routes.MapHttpRoute(

            name: "swagger_root",

            routeTemplate: "",

            defaults: null,

            constraints: null,

            handler: new RedirectHandler((message => message.RequestUri.ToString()), "swagger"));

 

 

            routes.MapMvcAttributeRoutes();

 

            routes.MapRoute(

                name: "Default",

                url: "{controller}/{action}/{id}",

                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }

            );

        }

    }

}

 

 

STEP 16-> Aynı route birden fazla olursa ilkini al demek

 

Not supported by Swagger 2.0: Multiple operations with path hatası alırsan. aşağıdakini aç

AppStart/SwaggerConfig.cs -> using System.Linq;

c.ResolveConflictingActions(apiDescriptions => apiDescriptions.First());

yeni bu yandakini yap ---------------> c.SchemaId(x => x.FullName);

veya route değiştir

[Route("api/Genel/getUrun/{barkod}")]

 

 

ÇOK ÖNEMLİ metodun SWAGER DE GÖZÜKMESİNİ İSTEMİYORSAN BUNU YAPARSIN

        using System.Web.Http.Description;

        [ApiExplorerSettings(IgnoreApi = true)]

        public void sonSoruEkle(string dil, List<SorularList> sorularLists)

 

STEP 17 -> BUNLARA BAKMASANDA OLUR

 

 

YORUM SATIRINDAN KALDIR VE AŞAĞIDAKİ KODU EKLE

 

 

ardından

 

 

 2024 Nisan 02 Salı
 1,064