Skip to content

Commit

Permalink
Added Swagger-UI Apis
Browse files Browse the repository at this point in the history
  • Loading branch information
wer_ltm committed Feb 27, 2017
1 parent c68ed21 commit 0492e6c
Show file tree
Hide file tree
Showing 7 changed files with 183 additions and 16 deletions.
1 change: 1 addition & 0 deletions src/EventCloud.Application/EventCloud.Application.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<DocumentationFile>bin\EventCloud.Application.XML</DocumentationFile>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
Expand Down
35 changes: 22 additions & 13 deletions src/EventCloud.Web/Controllers/AccountController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -39,10 +39,7 @@ public class AccountController : EventCloudControllerBase

private IAuthenticationManager AuthenticationManager
{
get
{
return HttpContext.GetOwinContext().Authentication;
}
get { return HttpContext.GetOwinContext().Authentication; }
}

public AccountController(
Expand Down Expand Up @@ -87,7 +84,7 @@ public async Task<JsonResult> Login(LoginViewModel loginModel, string returnUrl
loginModel.UsernameOrEmailAddress,
loginModel.Password,
loginModel.TenancyName
);
);

await SignInAsync(loginResult.User, loginResult.Identity, loginModel.RememberMe);

Expand All @@ -96,20 +93,32 @@ public async Task<JsonResult> Login(LoginViewModel loginModel, string returnUrl
returnUrl = Request.ApplicationPath;
}

return Json(new AjaxResponse { TargetUrl = returnUrl });
return Json(new AjaxResponse {TargetUrl = returnUrl});
}

private async Task<AbpLoginResult<Tenant, User>> GetLoginResultAsync(string usernameOrEmailAddress, string password, string tenancyName)
private async Task<AbpLoginResult<Tenant, User>> GetLoginResultAsync(string usernameOrEmailAddress,
string password, string tenancyName)
{
var loginResult = await _logInManager.LoginAsync(usernameOrEmailAddress, password, tenancyName);

switch (loginResult.Result)

try
{
case AbpLoginResultType.Success:
return loginResult;
default:
throw CreateExceptionForFailedLoginAttempt(loginResult.Result, usernameOrEmailAddress, tenancyName);
var loginResult = await _logInManager.LoginAsync(usernameOrEmailAddress, password, tenancyName);

switch (loginResult.Result)
{
case AbpLoginResultType.Success:
return loginResult;
default:
throw CreateExceptionForFailedLoginAttempt(loginResult.Result, usernameOrEmailAddress, tenancyName);
}
}
catch (Exception exception)
{

throw exception;
}

}
private async Task SignInAsync(User user, ClaimsIdentity identity = null, bool rememberMe = false)
{
Expand Down
5 changes: 3 additions & 2 deletions src/EventCloud.Web/Web.config
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,9 @@
<add key="ExternalAuth.Google.ClientSecret" value="" />
</appSettings>
<connectionStrings>

<add name="Default" connectionString="Server=localhost; Database=EventCloud; Trusted_Connection=True;" providerName="System.Data.SqlClient" />
<add name="Default" connectionString="Data Source=.; Database=EventCloud-Dev; User ID=sa; Password=123;" providerName="System.Data.SqlClient" />

<!--<add name="Default" connectionString="Server=localhost; Database=EventCloud; Trusted_Connection=True;" providerName="System.Data.SqlClient" />-->
</connectionStrings>
<!--
For a description of web.config changes see http://go.microsoft.com/fwlink/?LinkId=235367.
Expand Down
32 changes: 31 additions & 1 deletion src/EventCloud.WebApi/Api/EventCloudWebApiModule.cs
Original file line number Diff line number Diff line change
@@ -1,10 +1,14 @@
using System.Reflection;
using System;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Web.Http;
using Abp.Application.Services;
using Abp.Configuration.Startup;
using Abp.Modules;
using Abp.WebApi;
using Abp.WebApi.Controllers.Dynamic.Builders;
using Swashbuckle.Application;

namespace EventCloud.Api
{
Expand All @@ -20,6 +24,32 @@ public override void Initialize()
.Build();

Configuration.Modules.AbpWebApi().HttpConfiguration.Filters.Add(new HostAuthenticationFilter("Bearer"));

ConfigureSwaggerUi();
}


private void ConfigureSwaggerUi()
{
Configuration.Modules.AbpWebApi().HttpConfiguration
.EnableSwagger(c =>
{
c.SingleApiVersion("v1", "EventCloud.WebApi");
c.ResolveConflictingActions(apiDescriptions => apiDescriptions.First());


var baseDirectory = AppDomain.CurrentDomain.BaseDirectory;

var commentsFileName = "bin\\" + typeof(EventCloudApplicationModule).Assembly.GetName().Name +
".XML";
var commentsFile = Path.Combine(baseDirectory, commentsFileName);
c.IncludeXmlComments(commentsFile);

})
.EnableSwaggerUi("apis/{*assetPath}", c =>
{
c.InjectJavaScript(Assembly.GetAssembly(typeof(EventCloudWebApiModule)), "EventCloud.WebApi.Scripts.Swagger-Custom.js");
});
}
}
}
118 changes: 118 additions & 0 deletions src/EventCloud.WebApi/Api/Scripts/Swagger-Custom.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
var getCookieValue = function (key) {
var equalities = document.cookie.split('; ');
for (var i = 0; i < equalities.length; i++) {
if (!equalities[i]) {
continue;
}

var splitted = equalities[i].split('=');
if (splitted.length !== 2) {
continue;
}

if (decodeURIComponent(splitted[0]) === key) {
return decodeURIComponent(splitted[1] || '');
}
}

return null;
};

var csrfCookie = getCookieValue("XSRF-TOKEN");
var csrfCookieAuth = new SwaggerClient.ApiKeyAuthorization("X-XSRF-TOKEN", csrfCookie, "header");
swaggerUi.api.clientAuthorizations.add("X-XSRF-TOKEN", csrfCookieAuth);



/**
* Translator for documentation pages.
*
* To enable translation you should include one of language-files in your index.html
* after <script src='lang/translator.js' type='text/javascript'></script>.
* For example - <script src='lang/ru.js' type='text/javascript'></script>
*
* If you wish to translate some new texsts you should do two things:
* 1. Add a new phrase pair ("New Phrase": "New Translation") into your language file (for example lang/ru.js). It will be great if you add it in other language files too.
* 2. Mark that text it templates this way <anyHtmlTag data-sw-translate>New Phrase</anyHtmlTag> or <anyHtmlTag data-sw-translate value='New Phrase'/>.
* The main thing here is attribute data-sw-translate. Only inner html, title-attribute and value-attribute are going to translate.
*
*/
window.SwaggerTranslator = {
_words: [],

translate: function () {
var $this = this;
$('[data-sw-translate]').each(function () {
$(this).html($this._tryTranslate($(this).html()));
$(this).val($this._tryTranslate($(this).val()));
$(this).attr('title', $this._tryTranslate($(this).attr('title')));
});
},

_tryTranslate: function (word) {
return this._words[$.trim(word)] !== undefined ? this._words[$.trim(word)] : word;
},

learn: function (wordsMap) {
this._words = wordsMap;
}
};


/* jshint quotmark: double */
window.SwaggerTranslator.learn({
"Warning: Deprecated": "警告:已过时",
"Implementation Notes": "实现备注",
"Response Class": "响应类",
"Status": "状态",
"Parameters": "参数",
"Parameter": "参数",
"Value": "值",
"Description": "描述",
"Parameter Type": "参数类型",
"Data Type": "数据类型",
"Response Messages": "响应消息",
"HTTP Status Code": "HTTP状态码",
"Reason": "原因",
"Response Model": "响应模型",
"Request URL": "请求URL",
"Response Body": "响应体",
"Response Code": "响应码",
"Response Headers": "响应头",
"Hide Response": "隐藏响应",
"Headers": "头",
"Try it out!": "试一下!",
"Show/Hide": "显示/隐藏",
"List Operations": "显示操作",
"Expand Operations": "展开操作",
"Raw": "原始",
"can't parse JSON. Raw result": "无法解析JSON. 原始结果",
"Model Schema": "模型架构",
"Model": "模型",
"apply": "应用",
"Username": "用户名",
"Password": "密码",
"Terms of service": "服务条款",
"Created by": "创建者",
"See more at": "查看更多:",
"Contact the developer": "联系开发者",
"api version": "api版本",
"Response Content Type": "响应Content Type",
"fetching resource": "正在获取资源",
"fetching resource list": "正在获取资源列表",
"Explore": "浏览",
"Show Swagger Petstore Example Apis": "显示 Swagger Petstore 示例 Apis",
"Can't read from server. It may not have the appropriate access-control-origin settings.": "无法从服务器读取。可能没有正确设置access-control-origin。",
"Please specify the protocol for": "请指定协议:",
"Can't read swagger JSON from": "无法读取swagger JSON于",
"Finished Loading Resource Information. Rendering Swagger UI": "已加载资源信息。正在渲染Swagger UI",
"Unable to read api": "无法读取api",
"from path": "从路径",
"server returned": "服务器返回"
});


$(function () {
window.SwaggerTranslator.translate();
});

7 changes: 7 additions & 0 deletions src/EventCloud.WebApi/EventCloud.WebApi.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,10 @@
<HintPath>..\packages\Owin.1.0\lib\net40\Owin.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="Swashbuckle.Core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=cd1bb07a5ac7c7bc, processorArchitecture=MSIL">
<HintPath>..\packages\Swashbuckle.Core.5.5.3\lib\net40\Swashbuckle.Core.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="System" />
<Reference Include="System.Collections.Immutable, Version=1.2.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>..\packages\System.Collections.Immutable.1.3.1\lib\portable-net45+win8+wp8+wpa81\System.Collections.Immutable.dll</HintPath>
Expand Down Expand Up @@ -182,6 +186,9 @@
<Name>EventCloud.Core</Name>
</ProjectReference>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="Api\Scripts\Swagger-Custom.js" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<Import Project="$(SolutionDir)\.nuget\NuGet.targets" Condition="Exists('$(SolutionDir)\.nuget\NuGet.targets')" />
<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
Expand Down
1 change: 1 addition & 0 deletions src/EventCloud.WebApi/packages.config
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
<package id="Newtonsoft.Json" version="9.0.1" targetFramework="net461" />
<package id="Nito.AsyncEx" version="4.0.1" targetFramework="net461" />
<package id="Owin" version="1.0" targetFramework="net451" />
<package id="Swashbuckle.Core" version="5.5.3" targetFramework="net461" />
<package id="System.Collections.Immutable" version="1.3.1" targetFramework="net461" />
<package id="System.Linq.Dynamic" version="1.0.7" targetFramework="net461" />
</packages>

0 comments on commit 0492e6c

Please sign in to comment.